related_query_name - what is it?

881 views
Skip to first unread message

Petr Glotov

unread,
Aug 29, 2014, 9:43:31 PM8/29/14
to django...@googlegroups.com
Django doc says:

 ForeignKey.related_query_name
New in Django 1.6.
The name to use for the reverse filter name from the target model. Defaults to the value of related_name if it is set, otherwise it defaults to the name of the model:

# Declare the ForeignKey with related_query_name
class Tag(models.Model):
    article = models.ForeignKey(Article, related_name="tags", related_query_name="tag")
    name = models.CharField(max_length=255)

# That's now the name of the reverse filter
article_instance.filter(tag__name="important")

However, an object model doesn't have filter() method. I am trying to use related_query_name to filter a model M with a condition on the related objects R. The problem is that result includes instances of M which don't have related objects in R. But I would like to first understand what related_query_name is. Could someone explain? Thanks,

Petr

Petr Glotov

unread,
Aug 29, 2014, 10:27:38 PM8/29/14
to django...@googlegroups.com
Correction: first sentence of the question should read:
However, a model instance doesn't have filter() method. 

Simon Charette

unread,
Aug 29, 2014, 11:02:31 PM8/29/14
to django...@googlegroups.com
The documentation is wrong, it should be:


# That's now the name of the reverse filter
Article.objects.filter(tag__name="important")

I'll commit a documentation admonition and give you credit.

Thanks for spotting this!

Petr Glotov

unread,
Aug 29, 2014, 11:24:30 PM8/29/14
to django...@googlegroups.com
No problem.

I think I also found how to deal with M instances which are not related to R (R instances have foreign key to M). I tried M.filter(related_query_name_from_R__isnull=False) and it seems to work.
Reply all
Reply to author
Forward
0 new messages