Opened 5 years ago

Closed 5 years ago

Last modified 5 years ago

#31269 closed Bug (needsinfo)

Generic Relations on multi table inheritance does not behave as other fields

Reported by: Eduardo Klein Owned by: nobody
Component: contrib.contenttypes Version: 3.0
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Suppose we have the following models:

class Tag(models.Model):
    content_type = models.ForeignKey('contenttypes.ContentType', on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    obj = GenericForeignKey()


class Point(models.Model):
    name = models.CharField(max_length=256)
    tags = GenericRelation("tag")


class SpecificPoint(Point):
    pass

We create a specific_point instance as follow:

specific_point = SpecificPoint.objects.create(name="test")

Now we add a tag to the corresponding point instance :

point = Point.objects.get(pk=specific_point.id)
tag = point.tags.create()

When we do specific_point.tags.all() it returns en empty queryset, instead of a queryset containing the tag instance that we have created and that we would obtain doing point.tags.all()

I understand that the issue here is that the content_type associated with the tag instance is the "point" one and not the "specificpoint", but it's problematic since if we do specific_point.pk or specific_point.name or any other field that is not a generic relation, we would obtain exactly the same as point.pk or point.name, but the "logic" is broken for generic relations.

I'm not sure that this is a bug, but at least I think it deserves some consideration in the docs. If this is considered a bug, one possible solution would be to concatenate the tags from both models' content_types.

Change History (2)

comment:1 by Carlton Gibson, 5 years ago

Resolution: needsinfo
Status: newclosed

Hi Eduardo.

Thanks for the report.

I can see why you might want this. I can also see why it's unlikely to work, and I guess not trivial to fix.
(Or let me put it another way, it's quite a niche use-case, and I'm not at all sure it'd be worth the code to fix.)

The work-around is to resolve to the parent model, Point in your case, and then access the generic relation.
This is easy enough to do.

I could see a note being added to the GenericRelation docs, but looking it seems it would be quite clumsy wherever we put it.
Since someone searching will now find this, I'm a bit 😬 about adding such a note.

I'll say needsinfo: happy to look at a code or docs patch for this ticket, but pending that...

I hope that makes sense.

comment:2 by Carlton Gibson, 5 years ago

Component: Uncategorizedcontrib.contenttypes
Type: UncategorizedBug
Note: See TracTickets for help on using tickets.
Back to Top