making a retrieve api for a manytomany field
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__'
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.