我按顺序有3个表,像这样的外键
第一个表
class Orders(models.Model):
restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, blank=True, null=True)
order_number = models.AutoField(primary_key=True)
total_amount = models.DecimalField(max_digits=10, decimal_places=2)
第二个表将保留待售商品的记录
class OrderArticle(models.Model):
order = models.ForeignKey(Orders, on_delete=models.CASCADE)
article = models.ForeignKey(Articles, on_delete=models.CASCADE)
article_quantity=models.IntegerField(default=0)
prize=models.DecimalField(max_digits=10, decimal_places=2)
第3个表格是“文章”选项,每篇文章都有自己的选项,可以添加到文章中
class OrderArticleOptions(models.Model):
article_option = models.ForeignKey(ArticlesOptions, on_delete=models.CASCADE)
order_article = models.ForeignKey(OrderArticle, on_delete=models.CASCADE)
article_option_quantity = models.IntegerField(default=0)
price = models.DecimalField(max_digits=10, decimal_places=2)
现在我想使用Django rest框架在其中添加数据。我正在将数据添加到 Order表,像这样
Serilizer.py是
class OrderSerializer(serializers.ModelSerializer):
restaurant=RestaurantSerializer(required=False)
article=ArticlesSerializer(read_only=True, source='orderarticle_set' , many=True)
total_amount=serializers.DecimalField(required=False,max_digits=5, decimal_places=2)
tableid=serializers.IntegerField(required=False)
class Meta:
model = Orders
fields = [ 'order_number' , 'tableid' , 'total_amount' , 'ordertime' , 'order_status' ,'restaurant', 'article' ,]
def create(self, validated_data):
tableid = validated_data.get('tableid')
total_amount = validated_data.get('total_amount')
order_status = validated_data.get('order_status')
restaurant = validated_data.get('restaurant')
order_obj = Orders.objects.create(tableid=tableid,
total_amount=total_amount,order_status=order_status,
restaurant=restaurant
)
return order_obj
我的view.py是
class CreateOrderApi(APIView):
def post(self, request,restid):
serializer = OrderSerializer( data=request.data)
if serializer.is_valid():
obj_order = serializer.save(restaurant=Restaurant.objects.get(id=restid))
所以现在我想将数据添加到所有三个表中,关系是:在一个顺序中,我可以有多篇文章,而一篇文章可以有多篇文章选项。为此,将所有数据存储在1个电话中的最佳解决方案是什么?