如何将过滤器应用于Django rest-framework序列化器字段?

时间:2019-01-22 07:28:36

标签: django django-rest-framework

说我有三个这样的模型:

class Message(models.Model):
    text = models.TextField()
    img = models.ForeignKey('Image')


class Image(models.Model):
    deleted = models.BooleanField()
    url = models.URLField()
    msg = models.ForeignKey('Message')

class Tag(models.Model):
    deleted = models.BooleanField()
    name = models.CharField(max_length=10)
    msg = models.ForeignKey('Message')

序列化Message时,我需要将其tagurl删除,这意味着deleted字段是False。我希望自定义的SlugField应该像这样工作:

class ValidSlugField(serializers.SlugRelatedField):
    def __init__(self, *args, **kwargs):
        super(ValidSlugField, self).__init__(*args, **kwargs)

    def get_queryset(self):
        return super(ValidSlugField, self).get_queryset().filter(deleted=False)

但是get_queryset引发了错误。是否可以像这样创建一个“通用验证”字段?

1 个答案:

答案 0 :(得分:0)

我不明白为什么您要创建3个模型,也许您可​​以按照自己的意愿做类似的事情。

  1. 仅创建一个包含所有字段的模型。
  2. 创建一个自定义序列化器,该序列化器是:

    class MessageSerializer(serializers.Serializer):
        #all fields are here
    
  3. 使用此链接可以验证消息。 https://www.django-rest-framework.org/api-guide/serializers/#validation

    class MessageSerializer(serializers.Serializer):
        #all fields are here
        def validate(self,data):
            deleted = data.get('deleted')
            text = data.get('text')    
            img = data.get('img')
            if : #the shape of text or img for deleted is false
                 data['deleted'] = false 
                 return data
            return data #the shape of text or img for deleted is true
        def save(self):
              #use validated_data here
    
  4. 可以使用save()方法使用经过验证的数据,例如
    deleted = self.validated_data['deleted']