说我有三个这样的模型:
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
时,我需要将其tag
和url
删除,这意味着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
引发了错误。是否可以像这样创建一个“通用验证”字段?
答案 0 :(得分:0)
我不明白为什么您要创建3个模型,也许您可以按照自己的意愿做类似的事情。
创建一个自定义序列化器,该序列化器是:
class MessageSerializer(serializers.Serializer):
#all fields are here
使用此链接可以验证消息。 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
可以使用save()
方法使用经过验证的数据,例如
deleted = self.validated_data['deleted']