📜  django 通过 rest 进行多对多后更新方法 - Python 代码示例

📅  最后修改于: 2022-03-11 14:45:36.340000             🧑  作者: Mango

代码示例1
class GroupMembershipSerializer(ModelSerializer):
    class Meta:
        model = Membership
        fields = ('person',)

class GroupCreateSerializer(ModelSerializer):
     memberships = GroupMembershipSerializer(many=True, required=False)

    def create(self, validated_data):
        person_data = validated_data.pop('memberships')
        group = Group.objects.create(**validated_data)
        for person in person_data:
            d=dict(person)
            Membership.objects.create(group=group, person=d['person'])
        return group

    def update(self, instance, validated_data):
        person_data = validated_data.pop('memberships')
        for item in validated_data:
            if Group._meta.get_field(item):
                setattr(instance, item, validated_data[item])
        Membership.objects.filter(group=instance).delete()
        for person in person_data:
            d=dict(person)
            Membership.objects.create(group=instance, person=d['person'])
        instance.save()
        return instance

    class Meta:
        model = Group

class GroupCreateModelViewSet(ModelViewSet):
    serializer_class = GroupCreateSerializer
    queryset = Group.objects.all()