Django:GenericForeignKey 中的 content_type_id

2024-03-17

我根据文档编写了这个类,以便能够对应用程序中具有 id 的任何内容进行投票:

class Vote(models.Model):

    class Meta:
        unique_together = ('voted_id', 'voter_id', 'content_type', 'vote_type')

    voted_id        = models.PositiveIntegerField()
    vote_type       = models.BooleanField(null=True)
    content_type    = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    voter_id        = models.PositiveIntegerField()
    content_object  = GenericForeignKey('content_type', 'voter_id')

    def __str__(self):
        return self.content_object

然后在数据库表中,我有 5 列:

id, voted_id, vote_type, voter_id, content_type_id

我真的不明白 content_type_id 指的是什么:它是虚拟 id 吗?

因为根据我的理解,当我写道:

from forum.models import User, Vote
kdelanyd = User.objects.get(username='kdelanyd')
v = Vote(content_object=kdelanyd, voted_id=1, vote_type=False)
v.save()

我认为 content_type 持有“kdelanyd”引用,然后,在某种程度上它的 id :它没有。


  • 在你的数据库中可能有表是django_content_type. And content_type, content_type_id, content_object参考此表。它用于定义诸如“类型”之类的内容data.

  • Like a wheel,它可能是轮car or bicycle。在这种情况下car and bicycle is a content_object。和idcar and bicycle在表中django_content_type is content_type_id

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Django:GenericForeignKey 中的 content_type_id 的相关文章

随机推荐