I
I
Ilya Trusov2018-02-26 00:44:30
Django
Ilya Trusov, 2018-02-26 00:44:30

How to create related queries in django rest?

Hello. Immediately for example.
There is model A and model B.
The client that works with my API wants data from model B, but he does not have any data for this to make a request. Therefore, it goes to model A, receives data, and based on this data, goes to model B and receives data from there.
As a result, two requests. And if there are 5 such models? It is necessary to fulfill five requests at least. Is there any practice for implementing related requests in Django Rest?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Shubin, 2018-02-26
@idegree

I suspect you need something like this:

class CompanyContactSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.CompanyContact
        fields = ('id', 'type', 'value')


class CompanyDetailSerializer(serializers.ModelSerializer):
    contacts = CompanyContactSerializer(many=True, read_only=True)
    class Meta:
        model = models.Company
        fields = ('id', 'name', 'contacts')

So when you request a company, you immediately get its contacts. More details in the documentation .
However, it should be borne in mind that in this case there will be more requests to the database, but you can try to reduce them .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question