开发者

Can you explain this code?

I 开发者_如何学JAVAwas 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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜