需要在django api中为每个user_id存储更多车辆

时间:2017-08-16 23:25:12

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

我使用抽象用户定制了内置用户模型。我制作了另一个与用户模型一对一关系的模型车辆,它类似于每个用户的车辆。但它每个user_id存储一个车辆。我需要它来为每个用户存储多辆车。我的代码如下 -

Models.py

class User(AbstractUser):
  phone_number = models.IntegerField(null=True)
  otp = models.IntegerField(null=True)


class Vehicle(models.Model):
  user = models.OneToOneField(User)
  maker = models.CharField(max_length=500, blank=True)
  car_model = models.CharField(max_length=30, blank=True)

Serializer.py

class VehicleSerializer(serializers.ModelSerializer):
user_id = serializers.IntegerField()
class Meta:
    model = Vehicle
    fields = ('maker', 'car_model', 'user_id')                                                                      

def create(self, validated_data):
    maker = validated_data.pop('make', None)
    car_model = validated_data.get('car_model', None)
    user_id = validated_data.get('user_id', None)
    instance = self.Meta.model(**validated_data)

    if user_id is not None:
        instance.user_id = user_id
        instance.save()
    if car_model is not None:
        instance.car_model = car_model
        instance.save()
    return instance

Views.py

@api_view(['POST'])
def vehicle_add(request):
car_model = request.data.get('car_model')
user_id = request.user.id
serializer = VehicleSerializer(data={'user_id': user_id, 'car_model': car_model})
if serializer.is_valid():
    serializer.save()
    message = "i suceeded"
    return Response(message, status=status.HTTP_201_CREATED)
else:
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

我只需要知道如何在单个user_id下存储多个车辆。感谢

1 个答案:

答案 0 :(得分:0)

django one-to-one关系与听起来完全一样,它是从一个模型到一个模型的关系。您正在寻找的关系是many-to-one。查看文档:

https://docs.djangoproject.com/en/1.11/topics/db/examples/many_to_one/

如果您还有其他问题,请与我们联系!