I don't know when to use class GenericForeignKey in django.contrib.contenttypes module
I just read above link, but I don't know.
When I use that class??
When are that class useful?
Please give me some examples~
I don't know when to use class GenericForeignKey in django.contrib.contenttypes module
I just read above link, but I don't know.
When I use that class??
When are that class useful?
Please give me some examples~
The name says allot, it is a foreign key that can link to any content type i.e it can have a relation to any model. A nice example would be for a voting model where you could vote on a number of different objects and the vote instance in the vote model would just link to the model that you voted for.
class Article(models.Model):
.......
class Video(models.Model):
......
class Like(models.Model):
user = models.ForeignKey(User)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
obj = generic.GenericForeignKey()
Say you have these models above, The user can like an article and a video but you don't want to create a model for article likes and video likes separately because it creates unnecessary tables in you database and this can be painful especially if you have allot of models that can be liked. To solve this you create one Like model which can store all the likes of your website in one model. So when a user likes an article the like instance would have a relation to the user and to an article even though there is no explicit foreign key to the Article model, this would be done by setting the content type of the like model to the content type of the model you liked, which would be 'article' in this case (not you can use this :ContentType.objects.get_for_model(Article) to get the content type of a model) and then assign the id of the article to the object id.
article = Article.objects.get(pk=1)
article_ct = ContentType.objects.get_for_model(Article)
user = User.objects.get(username='admin')
Like.objects.create(user=user, content_type=article_ct, object_id=article.id)