问题描述
当我尝试将一些数据反序列化到对象中时,如果我包含一个唯一的字段并为其提供已经分配给数据库中对象的值,则会出现键约束错误。这是有道理的,因为它正在尝试创建具有已使用的唯一值的对象。
When I try to deserialize some data into an object, if I include a field that is unique and give it a value that is already assigned to an object in the database, I get a key constraint error. This makes sense, as it is trying to create an object with a unique value that is already in use.
是否有一种方法可以为get_or_create类型的功能ModelSerializer?我希望能够给序列化器一些数据,如果存在的对象具有给定的唯一字段,则只需返回该对象。
Is there a way to have a get_or_create type of functionality for a ModelSerializer? I want to be able to give the Serializer some data, and if an object exists that has the given unique field, then just return that object.
推荐答案
根据我的经验,nmgeek的解决方案无法在DRF 3+中使用,因为 serializer.is_valid()
正确地遵守了模型的unique_together约束。您可以通过删除 UniqueTogetherValidator
并覆盖序列化程序的 create
方法来解决此问题。
In my experience nmgeek's solution won't work in DRF 3+ as serializer.is_valid()
correctly honors the model's unique_together constraint. You can work around this by removing the UniqueTogetherValidator
and overriding your serializer's create
method.
class MyModelSerializer(serializers.ModelSerializer):
def run_validators(self, value):
for validator in self.validators:
if isinstance(validator, validators.UniqueTogetherValidator):
self.validators.remove(validator)
super(MyModelSerializer, self).run_validators(value)
def create(self, validated_data):
instance, _ = models.MyModel.objects.get_or_create(**validated_data)
return instance
class Meta:
model = models.MyModel
这篇关于Django REST Framework ModelSerializer的get_or_create功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!