Django REST通过ID更新外键

时间:2018-08-03 18:03:30

标签: django-rest-framework

问题:

我想更新一个外键字段,但我找不到我为什么不保存对该字段所做更改的错误。我希望能够更新clanwingman

serializer.py

class UpdateProfileInfoSerializer(serializers.Serializer):
    id = serializers.CharField(required=True)

    wingmanId = serializers.IntegerField(required=False)
    clanId = serializers.IntegerField(required=False)
    image = serializers.ImageField(required=False)
    titleImage = serializers.ImageField(required=False)
    description = serializers.CharField(required=False)

    class Meta:
        model = ProfileInfo
        fields = ['id', 'clanId', 'description', 'image', 'titleImage', 'wingmanId']

    def update(self, instance, validated_data):
        clan_id = validated_data.get('clanId')
        wingman_id = validated_data.get('wingmanId')

        if clan_id:
            if instance.clan:
                instance.clan.id = clan_id

        if wingman_id:
            if instance.wingman:
                instance.wingman.id = wingman_id

        instance.image = validated_data.get('image', instance.image)
        instance.titleImage = validated_data.get('titleImage', instance.titleImage)
        instance.description = validated_data.get('description', instance.description)
        instance.save()
        return instance

感谢您的帮助。我认为我做的事情根本上是错误的。

1 个答案:

答案 0 :(得分:0)

请尝试一下,我认为更好。

class UpdateProfileInfoSerializer(serializers.Serializer):
    id = serializers.CharField(required=True)

    wingmanId = serializers.IntegerField(required=False)
    clanId = serializers.IntegerField(required=False)
    image = serializers.ImageField(required=False)
    titleImage = serializers.ImageField(required=False)
    description = serializers.CharField(required=False)

    class Meta:
        model = ProfileInfo
        fields = ['id', 'clanId', 'description', 'image', 'titleImage', 'wingmanId']

    def update(self, instance, validated_data):
        clan_id = validated_data.get('clanId')
        wingman_id = validated_data.get('wingmanId')

        if clan_id:
            if instance.clan:
                try:
                    clan_obj = Clan.objects.get(id=clan_id)
                    instance.clan = clan_obj
                except:
                    pass

        if wingman_id:
            if instance.wingman:
                try:
                    wingman_obj = Wingman.objects.get(id=wingman_id) 
                    instance.wingman = wingman_obj
                except:
                    pass

        instance.image = validated_data.get('image', instance.image)
        instance.titleImage = validated_data.get('titleImage', instance.titleImage)
        instance.description = validated_data.get('description', instance.description)
        instance.save()
        return instance