Question

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?

Was it helpful?

Solution

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"

OTHER TIPS

It is simple, You may try

Person.__name__

With small modification to xelblch's answer: Using isinstance is a good idea, but you need to use content_object:

if notification.content_object and isinstance(notification.content_object, Person):
    # Your code here
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top