Django REST框架UniqueTogetherValidator

时间:2019-06-07 05:55:07

标签: python django django-rest-framework

问题描述:

DRF UniqueTogetherValidator显示一些奇怪的行为。 例如:

models.py

class MyModel1(models.Model):
    field1 = models.IntegerField()
    field2 = models.ForeignKey('MyModel2', on_delete...)

class MyModel2(models.Model):
    field3 = models.IntegerField()

serializer.py

from rest_framework.validators import UniqueTogetherValidator

class MyModel1Seriealizer(serializers.ModelSerializer):
    class Meta:
        model = MyModel1
        validators = [
            UniqueTogetherValidator(
                queryset=MyModel1.objects.all(),
                fields=('field1', 'field2_id')
            )
        ]

仅当条件由field1违反时,它会报告良好的400响应,并在non_field_errors中显示一条消息,但是当违反的字段为field2(或其字段{{1 }}),服务器会返回响应代码500(意味着Django在数据库/ ORM级别捕获了它)。

实际用例是here on my GitHub

完整追溯

_id

1 个答案:

答案 0 :(得分:0)

如果field2_id是外键,则不需要像这样放置字段。 只需将field2

from rest_framework.validators import UniqueTogetherValidator

class MyModel1Seriealizer(serializers.ModelSerializer):
    class Meta:
        model = MyModel1
        validators = [
            UniqueTogetherValidator(
                queryset=MyModel1.objects.all(),
                fields=('field1', 'field2')
            )
        ]

,您可以尝试发布json数据,如下所示:

{
  "field2": 1,
  "field1": "test",
}