外键序列化器更新方法

时间:2018-05-08 17:59:11

标签: django django-rest-framework

我有以下模特:

class Card(models.Model):
    thing = models.CharField(max_length=50, blank=True, null = True, )

class Responsibility(models.Model):
    name = models.CharField(max_length=50, blank=True, null=True, )
    card = models.ForeignKey(Card, related_name='responsibilities', blank=True, null=True, on_delete=models.CASCADE)

class Collaborator(models.Model):
    name = models.CharField(max_length=50, blank=True, null=True, )
    card = models.ForeignKey(Card, related_name='collaborators', blank=True, null=True, on_delete=models.CASCADE)

我的序列化器:

class CollaboratorSerializer(serializers.ModelSerializer):

    class Meta:
        model = Collaborator
        fields = '__all__'

class ResponsibilitySerializer(serializers.ModelSerializer):
    class Meta:
        model = Responsibility
        fields = '__all__'      


class CardSerializer(serializers.ModelSerializer):

    responsibilities = ResponsibilitySerializer(many=True,)
    collaborators = CollaboratorSerializer(many=True,)

    class Meta:
        model = Card
        fields = '__all__'

    def create(self, validated_data):
        responsibilities_data = validated_data.pop('responsibilities')
        collaborators_data = validated_data.pop('collaborators')

        card = Card.objects.create(**validated_data)
        for responsibility_data in responsibilities_data:
            Responsibility.objects.create(card=card, **responsibility_data)
        for collaborator_data in collaborators_data:
            Collaborator.objects.create(card=card, **collaborator_data)
        return card

创建并获得成功,我不知道如何为Card实现update()方法。示例request.data如下所示:

{u'collaborators': [{u'id': 8, u'card': 12, u'name': u''}, {u'name': u''}, {u'name': u''}], u'responsibilities': [{u'name': u'Name'}, {u'name': u'Age'}, {u'name': u'Address'}], u'id': 12, u'thing': u'Reader'}

在我的更新方法中,我想首先删除该特定卡的所有职责和协作者,然后从收到的数据中创建新的。

到目前为止我所拥有的:

def update(self, instance, validated_data):
    instance.responsibilities.all().delete()
    instance.collaborators.all().delete()
    .. NOT SURE ABOUT THIS PART ..

2 个答案:

答案 0 :(得分:1)

您可以覆盖ModelSerializer的update方法

class CardSerializer(serializers.ModelSerializer):

    ...

    def update(self, instance, validated_data):
        # do stuff here
        instance.collaborators.all().delete()
        instance.responsibilities.all().delete()

        res = validated_data.get('responsibilities', [])
        aList = [Responsibility(**vals) for vals in res]
        Responsibility.objects.bulk_create(aList)

        # same goes for collaborators

答案 1 :(得分:0)

此链接https://github.com/encode/django-rest-framework/blob/master/docs/topics/writable-nested-serializers.md可以为您提供帮助。此包非常适合更新并在序列化程序中创建相关字段而无需覆盖方法。我希望它对你有用