如果组名冲突,则更新同一组

时间:2017-03-11 02:27:32

标签: python django django-rest-framework

如果组用户的名称想要与已创建的组创建匹配,我如何更新同一组?如果我想更新而不是显示错误我应该在哪里工作?它是在验证功能还是创建功能?

这是我的序列化程序

class DeviceGroupSerializer(serializers.ModelSerializer):
    id = serializers.UUIDField(source='token', format='hex', read_only=True)
    devices = DeviceIdSerializer(many=True)

    class Meta:
        model = DeviceGroup
        fields = ['id','name', 'devices',]

    def validate(self, data):
        errors = {}
        try:
            name = data['name']
            if not bool(name):
                #empty or null
                errors['name'] = 'Name cannot be empty'
        except KeyError:
            if not (self.instance and bool(self.instance.name)):
                errors['name'] = 'Name is required'

        if len(data.get('devices', [])) == 0:
            errors['devices'] = 'Device(s) should be specified.'

        if bool(errors):
            raise serializers.ValidationError(errors)
        return data

    def create(self, validated_data):
        # for create - there is always name; we have already checked that in validation
        # TODO Further check for group-name clash - if yes, update the same group
        owner = validated_data['owner']
        name = validated_data['name']
        group = DeviceGroup.objects.create(owner=owner, name=name)

        tokens = [d['token'] for d in validated_data['devices'] ]
        BaseDevice.objects.filter(token__in=tokens, owner=owner).update(group=group)
        return group

def update(self, instance, validated_data):
        # for update - there may or may not be name
        # if it does, it refers rename

        owner = validated_data['owner']
        name = validated_data.get('name', None)
        if not name is None:
            instance.update(name=name)

        tokens = [d['token'] for d in validated_data['devices'] ]
        BaseDevice.objects.filter(token__in=tokens, owner=owner).update(group=instance)
        return instance

1 个答案:

答案 0 :(得分:1)

您想要update_or_create()

  

使用给定的kwargs更新对象的便捷方法,   必要时创建一个新的。默认值是字典   (字段,值)对用于更新对象。

根据您分享的内容,假设您希望更新DeviceGroup上的所有者,如果已存在具有给定DeviceGroup的{​​{1}},则会看起来如下所示:

name