Django:GenericForeignKey 中的 content_type_id

Django : content_type_id in GenericForeignKey

我根据文档写了这个 class 以便能够对应用程序中具有 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

然后在数据库 table 中,我有 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 :它没有。

  • 在您的数据库中可能 table 是 django_content_type。并且 content_typecontent_type_idcontent_object 在此 table 中引用。它用于定义 data.

  • 之类的任何内容
  • 就像一个wheel,它可能是carbicycle的轮子。在这种情况下 carbicyclecontent_object。而carbicycle在tabledjango_content_type中的id是content_type_id