2013-07-25 20 views
1

隨着簡化模型的:檢查content_object是某型號

class Notification(models.Model): 
    content_type = models.ForeignKey(ContentType, null=True) 
    object_id = models.PositiveIntegerField(null= True) 
    content_object = generic.GenericForeignKey('content_type', 'object_id') 

class Person(models.Model): 
    name = models.CharField(max_length=50) 

我應該如何檢查Notification的content_object是否是Person類的?

if notification.content_type: 
    if notification.content_type.name == 'person': 
     print "content_type is of Person class" 

這有效,但它只是不覺得正確,pythonic。有沒有更好的辦法?

+0

是'notification.content_type.model'是比較合適的。 – Rohan

回答

1

您可以使用isinstance(object, Class)測試,如果任何objectClass實例。

所以,在你的榜樣試試這個:

if notification.content_type: 
    if isinstance(notification.content_type, Person): 
     print "content_type is of Person class" 
0

它是簡單的,你可以試試

Person.__name__