验证永远不会被解雇

时间:2016-03-04 19:10:51

标签: django django-rest-framework

我有两种模式:

class Manufacturer(models.Model):
  name = models.CharField(max_length = 100)

class Car(models.Model):
  manufacturer = models.ForeignKey(Manufacturer, blank = True, null = True)

我的连载器:

class ManufacturerSerializer(serializers.ModelSerializer):
  class Meta:
    model = Manufacturer
    fields = ('id', 'name')

class CarSerializer(serializers.ModelSerializer):
  manufacturer = Manufact  

  class Meta:
    model = Car
    fields = ('id', 'name', 'manufacturer')

  def validate(self, attrs):
    try:
      attrs['manufacturer'] = Manufacturer.objects.get(pk = attrs['manufacturer'])
    except Manufacturer.DoesNotExist:
      raise ValidationError(_('Not found'))

    return attrs

我的观点:

class CarList(generics.ListCreateAPIView):
  queryset = Car.objects.all()
  serializer_class = CarSerializer

当我尝试添加新Car calling POST /cars/时,我收到验证错误manufacturer是必填字段。 Car模型希望manufacturer字段为Manufacturer个对象,但要使消息变小,我会将manufacturer_id传递给它。

我知道应该提出ValidationError以便解决此问题我向validate(..)添加了CarSerializer,因此在验证期间我会检查此ID的Manufacturer是否存在且我将它分配给attrs。

问题是validate(..)永远不会被调用我甚至尝试将post()方法添加到CarList视图并手动调用is_valid()但没有成功。

但我仍然得到验证错误,我认为这些错误来自模型。

1 个答案:

答案 0 :(得分:1)

它不起作用,因为你使事情变得复杂。 ManufacturerSerializer不是必需的(无论如何都是这个视图)。 By default 'manufacturer'字段将被表示为PrimaryKeyRelatedField,它会自动将manufacturer_id解析为Manufacturer对象,因此您不需要validate 1}}方法。

更新了序列化程序:

class CarPostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Car
        fields = ('id', 'name', 'manufacturer')

class CarGetSerializer(CarPostSerializer):
    manufacturer = ManufacturerSerializer()

更新了视图:

class CarList(generics.ListCreateAPIView):
    queryset = Car.objects.all()

    def get_serializer_class(self):
        if self.request.method == 'POST':
            return CarPostSerializer
        else:
            return CarGetSerializer