D
D
daniapog2020-06-06 23:09:54
Django
daniapog, 2020-06-06 23:09:54

How to output manytomany relation in django rest api?

Good evening, I have 2 models

class Person(models.Model):
    name = models.CharField(max_length=50)
    def __str__(self):
        return self.name 

class Film(models.Model):
    name = models.CharField(max_length=50)
    year = models.CharField(max_length=50, default=None)
    caption = models.CharField(max_length=50, default=None)
    person = models.ManyToManyField(Person)
    def __str__(self):
        return self.name


With these models, I can display the film and the actors in it, because in the Film model there is a person field with a connection.
It turns out such an api
{
    "data": {
        "name": "Терминатор",
        "person": [
            {
                "id": 1,
                "name": "Актер1"
            },
            {
                "id": 2,
                "name": "Актер2"
            }
        ]
    }
}


class FilmSerializers(serializers.ModelSerializer):
    class Meta:
        model= Film
        fields=('id','name')

class FilmDetailSerializers(serializers.ModelSerializer):
    person = PersonSerializers(many=True)
    class Meta:
        model= Film
        fields=('name','person')


I would like to be able to watch movies starring a certain actor, how can I do that?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
daniapog, 2020-06-06
@daniapog

Just added related_name
and specified it in the serializer
thanks

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question