I'm getting a very weird error when I try any method (delete, save, etc) on a model that holds a Generic Foreign Key. My model can hold different type of card types, and a job to process them:
class JobCards(models.Model):
class Meta:
unique_together = ('content_type', 'object_id')
content_type = models.ForeignKey(
ContentType,
on_delete=models.CASCADE,
help_text=_('Card type')
)
object_id = models.PositiveIntegerField(
help_text=_('Card id')
)
content_object = GenericForeignKey()
job = models.ForeignKey(
Job,
on_delete=models.CASCADE
)
So operations like:
JobCards.objects.create(content_object=card, job=job)
or
job_card = JobCards.objects.get(
job=job,
content_type=ContentType.objects.get_for_model(card),
object_id=card.id
)
job_card.delete()
will fail with such error.
I should mention that I put two GenericRelation in the card models, but even removing them doesn't change the end result:
job_cards = GenericRelation(JobCards, related_query_name='card')
Solved. Leaving this here just in case someone comes across the same issue. The problem was project related, not an issue with Django. The ContentType models I was using required a specific field, and somehow with a generic foreign key that is lost (while it seems just fine with a normal foreign key). Adding it as a property of the model did the trick:
@property
def required_field(self):
return self.content_object.some_linked_model.required_field