Home > Enterprise >  making a retrieve api for a manytomany field
making a retrieve api for a manytomany field

Time:01-23

I am making an API with django rest framework and what it's supposed to do is, it has to return the movies that a certain celebrity has acted or directed in.

And I dont know how to do that. because the film model has manytomany fields called filmActor and filmDirector and I want to preferably make this api by extending the ModelSerializer class.

# Models.py

class Celebrity(models.Model):
    celebID = models.AutoField(primary_key=True)
    nameOf = models.CharField(max_length=100, unique=True)
    details = models.TextField(null=True)

class Film(models.Model):
    filmID = models.AutoField(primary_key=True)
    title = models.CharField(max_length=150)
    filmActor = models.ManyToManyField(Celebrity, related_name='actor')
    filmDirector = models.ManyToManyField(Celebrity, related_name='director')

# Serializers.py
class CelebrityRetrieveSerializer(serializers.ModelSerializer):
    # TO BE DONE

CodePudding user response:

You can access many-to-many related objects thanks to "_set". Something like this should work:

class FilmSerializer(serializers.ModelSerializer):

    class Meta:
        model = Film
        fields = ('filmID', 'title')

class GenreRetrieveSerializer(serializers.ModelSerializer):
    film_set = FilmSerializer(many=True)
    
    class Meta:
        model = Genre
        fields = '__all__'

CodePudding user response:

The answer that @ThomasGth gave, works only if you have 1 foreign-key or many-to-many field.

to do this with two foreign keys, you have to name the field in your serializers.py, the name that was given to the related_name field in your models.py. so the code should be something like this:

class CelebrityRetrieveSerializer(serializers.ModelSerializer):
    class FilmSerializer(serializers.ModelSerializer):
        class Meta:
            model = Film
            fields = ('title',)
    
    actor = FilmSerializer(read_only=True, many=True,)
    director = FilmSerializer(read_only=True, many=True,)

    class Meta:
        model = Celebrity
        fields = '__all__'

You also have to make sure to give a value to related_name that does not conflict with the other names you have used in your code. for example if you set it to related_name = Film it could cause problems.

  •  Tags:  
  • Related