DRF 3 - 使用尽管表创建多对多更新/创建序列化程序

时间:2015-02-24 20:56:10

标签: python django django-rest-framework

我正在尝试在DRF 3中创建一个参考应用程序,以演示可以创建/更新模型的嵌套序列化程序。下面的示例代码在**之后使用“* create()参数进行炸弹,在尝试创建嵌套模型时必须是映射,而不是列表*”。我也不清楚我如何处理.update(),因为在某些情况下我只想建立其他关系(人)。

样本模型:

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)

序列化器和视图集:

from rest_framework.serializers import ModelSerializer
from rest_framework.viewsets import ModelViewSet
from app.models import Group, Person
class PersonSerializer(ModelSerializer):
    class Meta:
        model = Person
class GroupSerializer(ModelSerializer):
    persons = PersonSerializer(many=True)
    def create(self, validated_data):
        persons = validated_data.pop('persons')
        group = Group.objects.create(**validated_data)
        if persons: # Bombs without this check
            Person.objects.create(group=group, **persons)  # Errors here
        return group
    class Meta:
        model = Group

class PersonModelViewSet(ModelViewSet):
    serializer_class = PersonSerializer
    queryset = Person.objects.all()

class GroupModelViewSet(ModelViewSet):
    serializer_class = GroupSerializer
    queryset = Group.objects.all()

我正在尝试发布一些插入一个包含两个(相关)人员的JSON:

{
   "persons": [
      { "name" : "name 1" },
      { "name" : "name 2" }
   ],
   "name": "group name 1"
}

2 个答案:

答案 0 :(得分:12)

我不知道是否有更简单的方法,但我设法使其工作的唯一方法是在组序列化器中引用“通过”模型“成员资格”并为.create()编写自定义代码。 .update()。这似乎只是设置M2M FK的很多工作。如果有人知道更好的方式,我很乐意听到它。

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()

因此,您可以使用以下方式创建一个包含相关人员的新组:

 { 
     "name" : "Group 1", 
     "memberships" : [ 
         { "person" : 1 },
         { "person" : 2 }
     ]
 }

答案 1 :(得分:10)

使用此处显示的PrimaryKeyRelatedField

http://www.django-rest-framework.org/api-guide/relations/#primarykeyrelatedfield

class GroupSerializer(serializers.ModelSerializer):
    persons = serializers.PrimaryKeyRelatedField(
        many=True, queryset=Person.objects.all())

    class Meta:
        model = Group
        fields = ('name', 'persons')
例如,

首先创建每个人。 ID为1的人,姓名=" Bob"。 ID为2的人,姓名=" Tim"。然后使用他们的primary keys So:

将它们发布到REST端点
# Group create() REST endpoint data to POST
{'name': 'my group', 'persons': [1, 2]}

现在,您之前创建的人员是该组的成员。