Opened 3 years ago

Last modified 3 years ago

#19722 assigned Bug

GenericRelation in a subclass, filtering by a field of the GFK-declaring model fails

Reported by: ramiro Owned by: ramiro
Component: contrib.contenttypes Version: master
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

This was report in a comment by user 'nator' to #11263, is a different issue to the one initially discussed in that ticket. Quoting:

Say we have a non-abstract superclass and a subclass, and we add a GR relationship to the subclass:

class Order(models.Model):
    content_type = models.ForeignKey(ContentType)    
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey()
    status = models.CharField(max_length=10, default='ordered')
    
class Media(models.Model):
    order = generic.GenericRelation(Order)

class Photo(Media):
    title = models.CharField()

Photo.objects.filter(order__status='ordered').count()
--> doesn't break, but always returns 0.

The basic problem is that when the Order object is created Django inserts it into the DB using the content_type of Photo, but when the select is run Django realizes Order actually lives in Media and tries to use that content_type. So the inserts all "work", but the count() never finds them. It's a mismatch between the content_type_id when it runs the insert and select.

After digging through django/config/contenttypes/generic.py a bit I feel like the correct answer is to change the inserts to use the content_type of the class that actually contains the m2m relationship. (Media, in this case).

There is a proposed fix attached to that ticket.

Change History (1)

comment:1 Changed 3 years ago by ramiro

  • Owner changed from nobody to ramiro
  • Status changed from new to assigned
  • Triage Stage changed from Unreviewed to Accepted
Note: See TracTickets for help on using tickets.
Back to Top