DR3 Nested Serializers for "through" model

87 views
Skip to first unread message

litewaitt

unread,
Feb 24, 2015, 10:06:50 PM2/24/15
to django-res...@googlegroups.com
Before I burn a bunch of brain cells trying to determine how to handle this, consider this simple example of a "through" model like:

from django.db import models

class Person(models.Model):
    name = models.CharField(max_length=128)

class Group(models.Model):
    name = models.CharField(max_length=128)
    persons = models.ManyToManyField(Person, through='Membership')

class Membership(models.Model):
    person = models.ForeignKey(Person)
    group = models.ForeignKey(Group)

I need to create a ViewSet/Serializer that can create/update Group and it's related Person table.

I would hope I could handle one (or both) of these scenarios:

Create both Group and Person in the same ViewSet:

{
    "name": "Group 1", 
    "persons": [ 
        { "name" : "Person 1" },
        { "name" : "Person 2" }
    ]
}

or (assuming Person 1 and 2 exist)

{"name": "Group 1", "persons": [1, 2]}

I am not sure if I have to override the .create() method on the serializer, but if so it is unclear how to implement the related model (Person):

from rest_framework.serializers import ModelSerializer
from rest_framework.viewsets import ModelViewSet

from app.models import Group, Person

class PersonSerializer(ModelSerializer):
    class Meta:
        model = Person

class GroupSerializer(ModelSerializer):
    persons = PersonSerializer(many=True)

    def create(self, validated_data):
        return super().create(validated_data)

    class Meta:
        model = Group

class PersonModelViewSet(ModelViewSet):
    serializer_class = PersonSerializer
    queryset = Person.objects.all()

class GroupModelViewSet(ModelViewSet):
    serializer_class = GroupSerializer
    queryset = Group.objects.all()

If someone could verify this is possible and point me in a direction that would be great. 
Reply all
Reply to author
Forward
0 new messages