Difference

18 views
Skip to first unread message

Luvpreet Singh

unread,
Feb 15, 2017, 5:49:13 PM2/15/17
to Django users
What is the difference between realted_name and related_query_name ??

Michal Petrucha

unread,
Feb 16, 2017, 1:50:45 AM2/16/17
to django...@googlegroups.com
On Wed, Feb 15, 2017 at 12:48:21PM -0800, Luvpreet Singh wrote:
> What is the difference between realted_name and related_query_name ??

One is used as the name of the related manager on the remote side, the
other is used to traverse the relationship in queryset filters from
the remote side.

Let me try to illustrate that with an example.


class Reporter(models.Model):
name = models.TextField()


class Article(models.Model):
reporter = models.ForeignKey(Reporter, related_name="articles",
related_query_name="articles_written")
title = models.TextField()


So, when you have an instance of the Reporter model, you'd use the
related_name, which is “articles” here, to get a list of articles:

r = Reporter.objects.last()
r.articles.all()

However, if you want to get all reporters, who have written articles
with titles beginning with the letter “T”, you'd use the
related_query_name in the queryset filter:

Reporter.objects.filter(articles_written__title__startswith="T")

Does this make it more clear?

Cheers,

Michal
signature.asc

Luvpreet Singh

unread,
Feb 16, 2017, 2:05:13 AM2/16/17
to Django users
YES. Thank you very much for explaining this.
Reply all
Reply to author
Forward
0 new messages