With the simplified models:
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)
How should I check whether a Notification
's content_object is of the Person
class?
if notification.content_type:
if notification.content_type.name == 'person':
print "content_type is of Person class"
That works, but it just doesn't feel right nor pythonic. Is there a better way?
You can use isinstance(object, Class)
to test if any object
is instance of Class
.
So, in your example try this:
if notification.content_type:
if isinstance(notification.content_type, Person):
print "content_type is of Person class"