我想创建一个订单,我正在尝试用户保存订单。基本上,用户在下订单时必须选择他们想要的牛奶类型。在我看来,我该怎么做?我有点困惑。以下代码没有给我任何东西,数据没有保存。我该怎么做,有人可以帮忙吗?
这是我的档案。 models.py
MILK_CHOICES = (
('C', 'COW'),
('B', 'BUFFALO'),
('FC', 'FULL CREAM')
)
class MilkType(models.Model):
type = models.CharField(max_length = 20, choices = MILK_CHOICES, default = MILK_CHOICES[0][1])
quantity = models.PositiveIntegerField() # Stock
description = models.CharField(max_length = 100)
class Order(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
milk_choice = models.ForeignKey(MilkType)
qty = models.PositiveIntegerField(default = 1)
serializers.py
class UserSerializer(serializers.ModelSerializer):
orders = serializers.PrimaryKeyRelatedField(many=True, queryset=Order.objects.all())
class Meta:
model = CustomUser
fields = ('id', 'username', 'email')
class MilkTypeSerializer(serializers.ModelSerializer):
class Meta:
model = MilkType
fields = ('id', 'type', 'quantity', 'description')
class OrderSerializer(serializers.ModelSerializer):
user = serializers.ReadOnlyField(source = 'user.username')
class Meta:
model = Order
fields = ('id', 'user', 'milk_choice', 'qty')
views.py
class OrderList(APIView):
def get(self, request, format = None):
orders = Order.objects.all()
serializer = OrderSerializer(orders, many = True)
return Response(serializer.data)
def post(self, request, format = None):
serializer = OrderSerializer(data = request.data)
if serializer.is_valid():
serializer.save(user = request.user)
return Response(serializer.data, status = status.HTTP_201_CREATED)
return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST)
答案 0 :(得分:0)
在OrderSerializer中,将milk_choice
字段的序列化程序定义为MilkTypeSerializer。
class OrderSerializer(serializers.ModelSerializer):
user = serializers.ReadOnlyField(source = 'user.username')
milk_choice = MilkTypeSerializer()
class Meta:
model = Order
fields = ('id', 'user', 'milk_choice', 'qty')