A
A
Alexander2019-03-21 15:31:54
Django
Alexander, 2019-03-21 15:31:54

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",
        )

Question: How to get data from the intermediate Member model, namely the some_dop_info field?
So far, more than an hour of googling has led to nothing?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Tikhonov, 2019-03-21
@vintkor

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 question

Ask a Question

731 491 924 answers to any question