1👍
✅
You want update_or_create()
:
A convenience method for updating an object with the given kwargs,
creating a new one if necessary. The defaults is a dictionary of
(field, value) pairs used to update the object.
Based on what you’ve shared, this would look something like the following, assuming you want to update the owner on DeviceGroup
, if a DeviceGroup
with the given name
already exists:
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']
# created is a boolean telling us if a new DeviceGroup was created
group, created = DeviceGroup.objects.update_or_create(name=name, defaults={'owner': owner})
tokens = [d['token'] for d in validated_data['devices'] ]
BaseDevice.objects.filter(token__in=tokens, owner=owner).update(group=group)
return group
Source:stackexchange.com