Search code examples
djangodjango-generic-relations

Generic foreign key in Django showing error must be instance of Content Type


I have a following abstract Class

class Manufacturer(models.Model):
    company=models.CharField(max_length=255)

    class Meta:
        abstract = True

Now 2 classes inherit from above:-

class Car(Manufacturer):
    name = models.CharField(max_length=128)

class Bike(Manufacturer):
    name = models.CharField(max_length=128)

Now I want to link them with features, so I create following classes:-

class Feature(models.Model):
    name= models.CharField(max_length=255)
    limit=models.Q(model = 'car') | models.Q(model = 'bike')
    features = models.ManyToManyField(ContentType, through='Mapping',limit_choices_to=limit)

class Mapping(models.Model):
    category=models.ForeignKey(Category, null=True, blank=True)
    limit=models.Q(model = 'car') | models.Q(model = 'bike')
    content = models.ForeignKey(ContentType, on_delete=models.CASCADE,limit_choices_to=limit,default='')
    object_id = models.PositiveIntegerField(default=1)
    contentObject = GenericForeignKey('content', 'object_id')

    class Meta:
        unique_together = (('category', 'content','object_id'),)
        db_table = 'wl_categorycars'

But When i try creating instances in shell commands I get an error while creating mapping instance

"Mapping.content" must be a "ContentType" instance.

car1=Car(company="ducati",name="newcar")
bike1=Bike(company="bike",name="newbike")

cat1=Category(name="speed")

mapping(category=cat1, content=car1)  # ---> i get error at this point

How do I proceed with this?


Solution

  • You need to create your object with:

    Mapping(
       category=cat1,
       content=ContentType.objects.get_for_model(car1),
       object_id=car.id
    )
    

    By the way, I would have named the field content_type instead of content to avoid ambuiguity. See the official documentation for more information.