django many to many post update method via rest

Solutions on MaxInterview for django many to many post update method via rest by the best coders in the world

showing results for - "django many to many post update method via rest"
Edoardo
13 Jan 2019
1class GroupMembershipSerializer(ModelSerializer):
2    class Meta:
3        model = Membership
4        fields = ('person',)
5
6class GroupCreateSerializer(ModelSerializer):
7     memberships = GroupMembershipSerializer(many=True, required=False)
8
9    def create(self, validated_data):
10        person_data = validated_data.pop('memberships')
11        group = Group.objects.create(**validated_data)
12        for person in person_data:
13            d=dict(person)
14            Membership.objects.create(group=group, person=d['person'])
15        return group
16
17    def update(self, instance, validated_data):
18        person_data = validated_data.pop('memberships')
19        for item in validated_data:
20            if Group._meta.get_field(item):
21                setattr(instance, item, validated_data[item])
22        Membership.objects.filter(group=instance).delete()
23        for person in person_data:
24            d=dict(person)
25            Membership.objects.create(group=instance, person=d['person'])
26        instance.save()
27        return instance
28
29    class Meta:
30        model = Group
31
32class GroupCreateModelViewSet(ModelViewSet):
33    serializer_class = GroupCreateSerializer
34    queryset = Group.objects.all()