Search code examples
djangogeneric-relationsdjango-generic-relations

Django 1.10: Error when deleting a model with a GenericRelation


In my project I am mapping models inheriting from class A to models of type B using a GenericRelation via a third model, ABMapping.

models.py:

class A(models.Model):
    b = GenericRelation(B)

    class Meta:
        abstract = True

class ABMapping(models.Model):
    b = models.ForeignKey(B)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

class B(models.Model):
    x = ...
    y = ...

In the Django admin when I try to delete an object of child of A, I get an error, "Cannot resolve keyword u'object_id' into field. Choices are: x, y, id, abmapping." It seems like it's trying to take a field from ABMapping, but find it in B.

As you can see, I stripped down my models to the bare minimum, but the problem still happens.

Even when I delete all the ABMappings for the object of a child class of A, the same problem occurs.

All the seemingly related questions on StackOverflow relate to people complaining that the cascade-delete isn't happening... but I can't even get the top-level delete to take place.

Everything with these models has been working fine for a while... except this issue of deleting from the admin, which never worked from the start. What am I missing here?

Thanks!


Solution

  • Your A model doesn't have a relation with B, it has a relation with ABMapping. So the relation in A should be GenericRelation(ABMapping).

    There exists the concept of a many-to-many relation using another model as the connecting table, but one, that needs an actual ManyToManyField with a through=ABMapping argument, and two, I don't believe that can work if one of the two foreign keys is a GenericForeignKey.