Answer the question
In order to leave comments, you need to log in
How to get intermediate model data in Django Rest Framework serializer?
Example
#models.py
class User(models.Model):
username = models.CharField(max_length=50)
class Member(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
project = models.ForeignKey('currentApp.Project', on_delete=models.CASCADE)
some_dop_info = models.TextField()
class Project(models.Model):
title = models.CharField(max_length=250)
members = models.ManyToManyField(User, through=Member)
#serializers.py
class MemberSerializer(serializers.ModelSerializer):
class Meta:
model = Member
fields = (
'id',
'some_dop_info',
)
class ProjectSerializer(serializers.ModelSerializer):
members = MemberSerializer(many=True, read_only=True)
class Meta:
model = Project
fields = (
"title",
"members",
)
Answer the question
In order to leave comments, you need to log in
The Project model, in addition to the members descriptor, also has a member_set intermediate model descriptor, which returns a QuerySet Member. Accordingly, it can be reached by the serializer:
members = MemberSerializer(many=True, source='member_set.all', read_only=True)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question