【问题标题】:I don't know when to use class GenericForeignKey in django.contrib.contenttypes module我不知道何时在 django.contrib.contenttypes 模块中使用类 GenericForeignKey
【发布时间】:2013-02-08 06:48:53
【问题描述】:

我不知道何时在 django.contrib.contenttypes 模块中使用类 GenericForeignKey

https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#django.contrib.contenttypes.generic.GenericForeignKey

我刚刚看了上面的链接,但我不知道。

我什么时候使用那个类??

这个类什么时候有用?

请给我一些例子~

【问题讨论】:

    标签: django django-1.4


    【解决方案1】:

    名字说分配,它是一个可以链接到任何内容类型的外键,即它可以与任何模型有关系。一个很好的例子是投票模型,您可以在其中对许多不同的对象进行投票,并且投票模型中的投票实例只会链接到您投票的模型。

    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()
    

    假设您在上面有这些模型,用户可以喜欢文章和视频,但您不想分别为文章喜欢和视频喜欢创建模型,因为它会在您的数据库中创建不必要的表,这可能会很痛苦,尤其是如果你有很多可以喜欢的模型。为了解决这个问题,您创建了一个 Like 模型,它可以将您网站的所有喜欢存储在一个模型中。因此,当用户喜欢一篇文章时,即使 Article 模型没有明确的外键,like 实例也会与用户和文章有关系,这可以通过将 like 模型的内容类型设置为内容来完成您喜欢的模型的类型,在这种情况下为“文章”(不是您可以使用此 :ContentType.objects.get_for_model(Article) 来获取模型的内容类型),然后将文章的 id 分配给对象 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)
    

    【讨论】:

      猜你喜欢
      • 2013-01-05
      • 1970-01-01
      • 2020-09-19
      • 1970-01-01
      • 2011-07-10
      • 2017-09-13
      • 2014-12-19
      • 2021-09-13
      • 2021-12-26
      相关资源
      最近更新 更多