Opened 10 years ago

Closed 10 years ago

#7641 closed (duplicate)

Generic Relation reverse lookup not filtering by content type

Reported by: aaronfay Owned by: nobody
Component: Uncategorized Version: master
Severity: Keywords: newforms generic relations
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: UI/UX:


I've tested this issue in Django trunk (7844) and Django newforms-admin trunk (7844), this may be related to #5937 but my query resulting in discovery is different than his...

class Meta(models.Model):
    For adding meta data to any object through generic relations
    key = models.CharField(max_length=75)
    value = models.CharField(max_length=75)

    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()

    content_object = generic.GenericForeignKey()
    def __unicode__(self):
        return "%s (%s=%s)" % (self.content_object, self.key, self.value)

class Post(models.Model):
    title = models.CharField(max_length=75)
    description = models.TextField(null=True,blank=True)
    date = models.DateTimeField(
    meta = generic.GenericRelation(Meta)
    def __unicode__(self):
        return "%s" % self.title

class Page(models.Model):
    title = models.CharField(max_length=75)
    description = models.TextField(null=True,blank=True)
    meta = generic.GenericRelation(Meta)

    def __unicode__(self):
        return "%s" % self.title

class Thing(models.Model):
    name = models.CharField(max_length=75)
    meta = generic.GenericRelation(Meta)
    def __unicode__(self):
        return "%s" %
# Tests producing bug
>>> post = Post(title='my post')
>>> post.meta.add(Meta(key='mood', value='sad'))

>>> page = Page(title='my page')
>>> page.meta.add(Meta(key='foo', value='bar'))

# I accidentally found out (through a bad filter exception) that each Meta object gets a reverse lookup for 'post' and 'page'
# So then I try:
>>> Meta.objects.filter(page__title__icontains='my')
[<Meta: my post (mood=sad)>, <Meta: my page (foo=bar)>]

# Now lets add a Meta to a Thing
>>> thing = Thing(name='some thing')
>>> thing.meta.add(Meta(key='hello', value='world'))

# Run the same query as last time
>>> Meta.objects.filter(page__title__icontains='my')
[<Meta: my post (mood=sad)>, <Meta: my page (foo=bar)>, <Meta: some thing (hello=world)>]

# Thing doesn't even contain a 'title' field, but it still ends up in the results

Change History (1)

comment:1 Changed 10 years ago by Malcolm Tredinnick

Resolution: duplicate
Status: newclosed

Almost certainly the same root cause as #5937. Generic relations don't filter on all the right columns, however it may manifest itself. So closing as a dupe, since I'm already working on the other one.

Note: See TracTickets for help on using tickets.
Back to Top