Let's start with the models used in the django documentation on the M2M relationship, which uses a pass-through argument to point to a 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']
Suppose now I want to get a read-write rest for a group model, which also contains all the people within each group, sorted by date_joined field . I would like to get json serialized (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')
Although it works well for read operations, it does not for write operations. How do I define a serializer so that, given the serialization described above, it continues:
- Create a group object
- Add each member to the group (by creating the Membership object)
source share