使用直通表在modelSerializer中创建多对多创建/更新

时间:2018-01-06 10:02:13

标签: django django-rest-framework

以下是我的模特

   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)
        fee = models.IntegerField()

在Serializer级别,我想通过会员保存与人M2M相关的会员和群组我正在尝试这样的事情。         class GroupMembershipSerializer(ModelSerializer):             类Meta:                 model =会员资格                 fields =(' person',' fee',)

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

        def create(self, validated_data):
            person_data = validated_data.pop('memberships')
            fee = validated_data.pop('fee')
            # Stuck here ! What should i do here ?
            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()

除了工作正常之外,如何在该表中节省费用

1 个答案:

答案 0 :(得分:1)

如果您收到fee的一个值并希望将其应用于所有成员资格,只需将其传递给Membership.objects.create()

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