2013-07-25 17 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__