djangopython-3.xdjango-contenttypes

Django : content_type_id in GenericForeignKey


I wrote this class according to documentation to be able to vote on anything with an id in the application :

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

Then in the database table, I have 5 columns :

id, voted_id, vote_type, voter_id, content_type_id

I don't really understand what is content_type_id referring to : is it a virtual id ?

Because in my understanding, when I wrote :

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

I thought that content_type was holding 'kdelanyd' reference and then, somewhat its id : it does not.


Solution