pythondjangoforeign-keysdjango-contenttypesgeneric-foreign-key

Error when Making Migration for Django Project


When I completed writing my models, one models, I used GenericForeignKey. Here is the code

from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey

# Create your models here.
class Tag(models.Model):
    label = models.CharField(max_length=255)
    
class TaggedItem(models.Model):
    # what tag applied to what object 
    tag = models.ForeignKey(Tag, on_delete=models.CASCADE)  
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()  
    content_type = GenericForeignKey()

but I counter this error which I could not solve.

SystemCheckError: System check identified some issues:

ERRORS:
like.LikedItem.content_type: (contenttypes.E003) 'LikedItem.content_type' is not a ForeignKey.
        HINT: GenericForeignKeys must use a ForeignKey to 'contenttypes.ContentType' as the 'content_type' field.
tags.TaggedItem.content_type: (contenttypes.E003) 'TaggedItem.content_type' is not a ForeignKey.
        HINT: GenericForeignKeys must use a ForeignKey to 'contenttypes.ContentType' as the 'content_type' field.

Your support is appreciated

I tried multiple solution that I found through my research in the Internet, but none of those fixed the issue.

One of the change I did is: content_type = GenericForeignKey('content_type', 'object_id')


Solution

  • The error is arising because you are overwriting the ForeignKey content_type field with a GenericForeignKey.

    from django.db import models
    from django.contrib.contenttypes.models import ContentType
    from django.contrib.contenttypes.fields import GenericForeignKey
    
    # Create your models here.
    class Tag(models.Model):
        label = models.CharField(max_length=255)
    
    class TaggedItem(models.Model):
        # what tag applied to what object 
        tag = models.ForeignKey(Tag, on_delete=models.CASCADE)  
        content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
        object_id = models.PositiveIntegerField()  
        content_object = GenericForeignKey('content_type', 'object_id')  # Corrected field