M
M
mx60012020-05-06 11:58:04
Django
mx6001, 2020-05-06 11:58:04

How to use select related in Django with an existing object?

I have an existing user object which has many related fields via select_relatedand prefetch_related:

user = models.User.objects.first().select_related(...).prefetch_related(...)


I need to get all the articles of this user through the model Article(not through user.article_set). Model Articlehas ForeignKeyper model User:

articles = models.Article.objects.filter(user=user)


I want all objects in querysety to Article have an existing object user, i.e. do something like this:

articles = models.Article.objects.filter(user=user).select_related(user)

or
articles = models.Article.objects.filter(user=user).annotate(user=user)

But these examples do not work, is this implementation possible in any form? Going through the loop articlesand assigning everything to them user'ais not very concise.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question