模型中的unique_together。模型与序列化程序的uniquetogethervalidator

如果我有一个model A,其中(field1和field2是模型的字段)

`unique_together = ('field1','field2')`

Meta类中,而serializerserializer上的模型model A的{​​{1}},那么为什么我应该或为什么不应该在Meta中使用Uniquetogethervalidator序列化程序。如果我们已经在模型中有条件,为什么我们需要这个验证器?还是在模型中使用unique_constraint和在序列化器中使用uniquetogethervalidator有什么区别?

digohao 回答:模型中的unique_together。模型与序列化程序的uniquetogethervalidator

  

如果模型中已有条件,为什么要使用此验证器?

使所有验证都保留在序列化器上,而无需进入模型层;为了避免进行分区验证,可以这么说。

DRF验证遵循与Django不同的想法-Django尝试在表单级别进行一些验证,然后将其余的委托给模型(例如unique_together),而DRF尝试在序列化器级别合并所有验证

  

在模型中使用unique_constraint和在序列化器中使用uniquetogethervalidator有什么区别?

DRF中的UniqueTogether验证程序是在序列化程序中实现的,即在将数据传递到下一级(模型)之前。同样,此验证器也是在纯Python中实现的,这就是queryset必须使用UniqueTogether参数来检查其中字段唯一性的原因。

OTOH,模型中的unique_together实现了数据库约束,该约束仅在将对象保存在DB上时检查,并且此检查由DB本身完成/强制执行。

if you have unique_together constraints on the model and if you're using DRF ModelSerializer,then those constraints are converted to a UniqueTogetherValidator object by DRF,以便它可以在将数据传递到数据库之前进行验证。

本文链接:https://www.f2er.com/3048212.html

大家都在问