Let's start from the models used in the django docs about the M2M relationship that uses the through argument to point to the model that will act as an intermediary.
class Person(models.Model):
name = models.CharField(max_length=128)
def __unicode__(self):
return self.name
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person,
through='Membership')
def __unicode__(self):
return self.name
class Membership(models.Model):
person = models.ForeignKey(Person)
group = models.ForeignKey(Group)
date_joined = models.DateField()
class Meta:
ordering = ['date_joined']
Assume now I want to have a rest read-write view for the Group model which contains also all the Person inside each group, ordered by date_joined field. The json serialization I would like to obtain is the following (the members are described only with their id):
{
"id": 1,
"name": "U2",
"members": [
20,
269,
134,
12,
]
}
I wrote a serializer:
class GroupSerializer(serializers.ModelSerializer):
members = serializers.SlugRelatedField(source='membership_set',
many=True,
read_only=False,
slug_field='person_id',
required=True)
class Meta:
model = Group
fields = ('id', 'name', 'members')
While for read operations it works well, it doesn't for writing. How should I define the serializer so that, given the above defined serialization, it will proceed by:
- Create the Group object
- Add each members to the Group (by creating a Membership object)