Django:GenericForeignKey中的content_type_id

时间:2018-12-18 19:47:50

标签: django python-3.x django-contenttypes

我根据文档编写了此类,以便能够对应用程序中具有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有点:它没有。

1 个答案:

答案 0 :(得分:1)

  • 在您的数据库中,表可能是django_content_type。并且在此表中引用了content_typecontent_type_idcontent_object。它用于定义data的“类型”之类的内容。

  • wheel一样,它可能是carbicycle的转盘。在这种情况下,carbicyclecontent_object。表carbicycledjango_content_type的ID为content_type_id

相关问题