DRF 3.0:使用Django Rest Framework在相关的Serializer中共享一个UniqueTogetherValidator

时间:2015-12-18 08:51:42

标签: django-rest-framework

我正在处理一组模型类,它们通过继承共享一些共同的属性:

class MyBaseModel(models.Model):

    class Meta:
        abstract = True
        unique_together = (('system', 'code',),)

    id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True, ...
    system = models.ForeignKey(System, ...
    code = models.CharField(...
    ...


class ModelA(MyBaseModel):
    ...

class ModelB(MyBaseModel):
    ...

请注意Meta类中存在unique_together约束。

类似的层次结构对于相应的序列化器来说很方便; 我不确定是否需要明确指定UniqueTogetherValidator, 目前正在对此进行调查。 但万一,我想知道如何在基本序列化程序类中表达它,因为它 需要一个事先不知道的查询集:

from rest_framework import serializers
from rest_framework.validators import UniqueTogetherValidator


class MyBaseModelSerializer(serializers.ModelSerializer):

    class Meta:
        exclude = ['date_created', 'created_by', ...

        validators = [
            UniqueTogetherValidator(
                queryset=???.objects.all(),
                fields=('system', 'code')
            )
        ]


class ModelASerializer(MyBaseModelSerializer):
    class Meta(MyBaseModelSerializer.Meta):
        model = ModelA
    ...


class ModelBSerializer(MyBaseModelSerializer):
    class Meta(MyBaseModelSerializer.Meta):
        model = ModelB
    ...

如何避免为每个派生类重复它,如下所示 例子?

from rest_framework import serializers
from rest_framework.validators import UniqueTogetherValidator


class MyBaseModelSerializer(serializers.ModelSerializer):

    class Meta:
        exclude = ['date_created', 'created_by', ...


class ModelASerializer(MyBaseModelSerializer):
    class Meta(MyBaseModelSerializer.Meta):
        model = ModelA
        validators = [
            UniqueTogetherValidator(
                queryset=ModelA.objects.all(),
                fields=('system', 'code')
            )
        ]
    ...


class ModelBSerializer(MyBaseModelSerializer):
    class Meta(MyBaseModelSerializer.Meta):
        model = ModelB
        validators = [
            UniqueTogetherValidator(
                queryset=ModelB.objects.all(),
                fields=('system', 'code')
            )
        ]
    ...

2 个答案:

答案 0 :(得分:1)

模型序列化程序从模型的UniqueTogetherValidator约束中添加unique_together。你没有单独给予。

答案 1 :(得分:0)

需要覆盖

unique_together = (('system', 'code',),)
非抽象模型中的