1

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!

TAH
  • 1,658
  • 1
  • 19
  • 37

1 Answers1

3

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.

RemcoGerlich
  • 30,470
  • 6
  • 61
  • 79
  • ...and that was what I was missing! THANK YOU. I'm rather bewildered that (a) the thing worked for so long as originally written, and (b) making the change you suggest worked seamlessly without breaking anything. But I'll take it! Thanks again. – TAH Dec 15 '16 at 09:39