如何使用Django Rest Framework向用户添加汽车

时间:2015-11-17 18:24:54

标签: python django django-models django-views django-rest-framework

当我尝试为我的用户添加汽车时,这就是正在发生的事情

 "username": [
"A user with that username already exists."]

这是我的模型,我使用的是Django auth用户模型 有我的模特

class Car(models.Model): 
"""
CAR Table with a ForeingKey from USER Table

"""
user = models.ForeignKey(User, related_name='cars')
model = models.CharField(max_length=50)
color = models.CharField(max_length=20)
year = models.IntegerField()
seats = models.IntegerField()


def __unicode__(self):
    return u'%d: %s: %s: %d' % (self.id, self.model, self.color, self.year)

我的序列化工具

class CarSerializer(serializers.ModelSerializer):
class Meta:
    model = Car
    fields = (
        'model', 
        'color', 
        'seats'
        )      

class AddCarSerializer(serializers.ModelSerializer):
car = CarSerializer()
class Meta:
    model = User
    fields = (
        'username',
        'car'
        )

这是我的观点

class AddCarForUser(APIView):
authentication_classes = (TokenAuthentication,)
permission_classes = (IsAuthenticated,)

def put(self, request):
    car = AddCarSerializer(data = request.data)
    car.is_valid(raise_exception = True)
    car.save()
    return Response(status=status.HTTP_201_CREATED)

这就是我在Put请求中发送的内容

{
"username": "root",
"car": {
    "model": "Seat Ibiza",
    "color": "Verde",
    "seats": "4" 
}}

1 个答案:

答案 0 :(得分:2)

您的代码无效,因为您使用serializer.ModelSerializerusername类的User属性必须是唯一的,这就是为什么它无法验证它。要解决此问题,请按照以下步骤操作。

  1. 更新序列化程序AddCarSerializer。我们添加了一个自定义字段username来处理在没有唯一的情况下传递的用户名,只是一个简单的CharField。我们添加create函数,因为嵌套的序列化程序无法处理创建或更新框:
  2. class AddCarSerializer(serializers.Serializer):
        # add username custom field
        username = serializers.CharField()
        car = CarSerializer()
    
        class Meta():
            fields = (
                'username',
                'car'
            )
    
        def create(self, validated_data):
            """ Add car to an user
            """
            tmp_car = validated_data.pop('car')
                user = User.objects.get(username=validated_data['username'])
            car = Car.objects.create(
                user=user,
                model=tmp_car['model'],
                color=tmp_car['color'],
                seats=tmp_car['seats'],
            )
    
            return car
    
    1. 更新您的观点:
    2. class AddCarForUser(APIView):
      
          def put(self, request):
              serializer = AddCarSerializer(data = request.data)
              if serializer.is_valid():
                  serializer.save()
                  return Response(status=status.HTTP_201_CREATED)
              return Response(status=status.HTTP_400_BAD_REQUEST)
      
      1. 更新您的Car模型,因为当我们向用户添加汽车时,year属性不存在,然后添加null=True
      2. class Car(models.Model):
            user = models.ForeignKey(User, related_name='cars')
            model = models.CharField(max_length=50)
            color = models.CharField(max_length=20)
            year = models.IntegerField(null=True)
            seats = models.IntegerField()
        

        它应该有效。不要忘记处理错误,就像通过的用户名不存在一样。