A
A
adrenalinruslan2021-06-02 21:40:53
Django
adrenalinruslan, 2021-06-02 21:40:53

How to get an additional object ( QuerySet )?

For example, I get a list of who the user is following:

user = User.objects.get(id=1)
subscriptions = Subscription.objects.filter(user=user)


Returned:
[
    {
        "id": 1,
        "user": 1 (User object),
        "author": 2 (User object)
    }
]


But, I also want to display all the recipes of the author (author). Yes, you can do it this way, but it doesn't fit: And now the question is, can this be somehow combined at the query level into the database? What would I get back a response like this:
recipes = subscriptions[0].author.recipes.all()

[
    {
        "id": 1,
        "user": 1,
        "author": 2,
        "recipes": [
            {
                "id": 1,
                "name": "Name"
            }
        ]
    }
]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2021-06-03
@pyHammer

adrenalinruslan can be done at the database level, but then you will have to group by user on the backend, for example through pandas, but at the output you will no longer get a QuerySet

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question