tags:

views:

110

answers:

1

I was studying cnprog (a django clone of stackoverflow) and came across this code:

class Comment(models.Model):
    content_type   = models.ForeignKey(ContentType)
    object_id      = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')
    user           = models.ForeignKey(User, related_name='comments')
    comment        = models.CharField(max_length=300)
    added_at       = models.DateTimeField(default=datetime.datetime.now)

So my question is "what is the use of content_object? And when to use Generic relations?"

thanks

+3  A: 

I recently stumbled upon this awesome feature of Django and reading the docs page made it all clear.

To expand a little bit, generic relations is when you want a Model to be able to be associated to more than 1 other Model. In the example above, because it is using a GenericKey, a Comment can belong to multiple models (like a Question or an Answer, etc.)

In my particular use sample, I had an AddressProfile model and I wanted both the User model and the Company model to be able to have an AddressProfile. I initially simply had two ForeignKeys in the AddressProfile with null=True so I could specify whichever relation it was, but the GenericKey functionality made it much cleaner for me.

Paolo Bergantino
Thanks for the link. I was looking at http://www.djangoproject.com/documentation/models/generic_relations/#sample-usage but could get much from it.
Baha
The Django documentation has a search feature too.
dannyroa
Note that generic relations will make your database take a huge hit when querying across them; resolve the object ID yourself whenever possible.
Ignacio Vazquez-Abrams
thanks for the tip, ignacio
Baha