1

使用简化模型:

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)

我应该如何检查 aNotification的 content_object 是否属于Person该类?

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

那行得通,但它只是感觉不对,也不像pythonic。有没有更好的办法?

4

2 回答 2

1

您可以isinstance(object, Class)用来测试是否objectClass.

所以,在你的例子中试试这个:

if notification.content_type:
    if isinstance(notification.content_type, Person):
        print "content_type is of Person class"
于 2013-07-25T08:42:50.020 回答
0

很简单,你可以试试

Person.__name__
于 2013-07-25T07:09:31.297 回答