由Django rest验证不在模型中的字段

时间:2017-03-29 18:36:20

标签: django django-rest-framework

我有一个模特:

class EventTracker(models.Model):
"""
Track events of user's behaviors
"""
class Meta:
    verbose_name = "EventTracker"
    verbose_name_plural = "EventTrackers"
    unique_together = ("application", "label")

application = models.ForeignKey(Application, related_name='events')
label = models.CharField(max_length=50)
count = models.PositiveIntegerField(default=0)
value = models.IntegerField(null=True)

def __str__(self):
    return "[{}] {}".format(self.application, self.label)

这是我对这个型号的序列化器:

class EventTrackerSerializer(serializers.ModelSerializer):
subscriber_id = serializers.IntegerField(min_value=1)

class Meta:
    model = EventTracker
    fields = ('id', 'application', 'label', 'count', 'value', 'subscriber_id')
    write_only_fields = ('subscriber_id', )
    read_only_fields = ('count',)

subscriber_id是不属于此模型的字段。但是请求数据必须让subscriber_id做一件事。所以我想在序列化器中验证它。我不知道如何验证它。我尝试过如上所述,它引发了错误:

This may be because you have a writable field on the serializer class that is not a valid argument to.....

那我该怎么办?

1 个答案:

答案 0 :(得分:0)

首先,您应该更明确地了解自己想要做什么。我们不知道该字段的用途,也不知道它是什么/如何验证它的可读性,所以我做了一些猜测。

假设它只写:

subscriber_id = serializers.IntegerField(min_value=1, write_only=True)

请注意,write_only_fields已被删除一段时间。 接下来,您必须手动编写序列化程序的创建/更新。创建示例:

class EventTrackerSerializer(serializers.ModelSerializer):
    ...
    def create(self, validated_data):
        subscriber_id = validated_data.pop('subscriber_id')
        instance = EventTracker.objects.create(**validated_data)
        return instance