Django: way to test what class a generic relation content_object is?

Posted by bitbutter on Stack Overflow See other posts from Stack Overflow or by bitbutter
Published on 2010-05-06T15:00:23Z Indexed on 2010/05/06 15:08 UTC
Read the original article Hit count: 287

Filed under:
|
|

In my project I have a class, NewsItem. Instances of NewsItem act like a wrapper. They can be associated with either an ArtWork instance, or an Announcement instance.

Here's how the NewsItem model looks:

class NewsItem(models.Model):   
 content_type = models.ForeignKey(ContentType)
 object_id = models.PositiveIntegerField()
 content_object = generic.GenericForeignKey('content_type', 'object_id')
 date = models.DateTimeField(default=datetime.datetime.now,)
 class Meta:
  ordering = ('-date',)
 def __unicode__(self):
  return (self.title())

In a template I'm dealing with a NewsItem instance, and would like to output a certain bunch of html it it's 'wrapping' an Artwork instance, and a different bunch of html if it's wrapping an Announcement instance. Could someone explain how I can write a conditional to test for this?

My first naive try looked like this:

{% if news_item.content_object.type=='Artwork' %}do this{% else %}do that{% endif %}

© Stack Overflow or respective owner

Related posts about django

Related posts about polymorphic