无法在同一序列化程序中获取外键表的数据

时间:2019-10-21 19:08:08

标签: django django-rest-framework

订单表

class Orders(models.Model):
    restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, blank=True, null=True)
    tableid=models.IntegerField()
    orderid=models.IntegerField()
    total_amount = models.DecimalField(max_digits=10, decimal_places=2)

Articles表可保存披萨之类的文章

class OrderArticle(models.Model):
    order = models.ForeignKey(Orders, on_delete=models.CASCADE)
    article = models.ForeignKey(Articles, on_delete=models.CASCADE)
    # article_options = models.ManyToManyField(ArticlesOptions)

文章选项可保存多余的顶部或任何可用的选项

class OrderArticleOptions(models.Model):
    # order = models.ForeignKey(Orders, on_delete=models.CASCADE)
    article_option = models.ForeignKey(ArticlesOptions, on_delete=models.CASCADE)
    order_article = models.ForeignKey(OrderArticle, on_delete=models.CASCADE)
    quantity = models.IntegerField(default=1)
    price = models.DecimalField(max_digits=10, decimal_places=2)

编辑

文章选项表

class ArticlesOptions(models.Model):
    articleoptionrestaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE , blank=True, null=True)
    optionname = models.ForeignKey(ArticlesOptionsName, on_delete=models.CASCADE, related_name="optionnames")
    min = models.IntegerField()
    max = models.IntegerField()
    choice_price = models.DecimalField(max_digits=10, decimal_places=2)
    choice = models.CharField(max_length=255)
    def __str__(self):
        return str(self.optionname)

所以现在的问题是,当我尝试一次序列化获取所有数据时,我无法获取。我正在使用此示例获取

https://www.django-rest-framework.org/api-guide/relations/

编辑

我的serilizers是

class OrderSerializer(serializers.ModelSerializer):
    restaurant=RestaurantSerializer(required=False)
    class Meta:
        model = Orders
        fields = ['restaurant','tableid', 'orderid', 'total_amount']

class ArticlesSerializer(serializers.ModelSerializer):
    order = OrderSerializer(read_only=True)
    article=ListArticleSerializer(read_only=True)

    class Meta:
        model = OrderArticle
        fields = ['order', 'article']


class ArticlesOptionSerializer(serializers.ModelSerializer):
    article_option = ListCategoriesSerializer(  read_only=True)
    order_article=ArticlesSerializer(read_only=True)

    class Meta:
        model = OrderArticleOptions
        fields = ['article_option','order_article','quantity','price']
    depth=1

我的view.py是

class OrderedArticles(APIView):
    def get(self, request, restid):

        Options=OrderArticleOptions.objects.filter(order_article=1)
        orderserlizer=ArticlesOptionSerializer(Options , many=True)
        return Response(success_response({'orders': orderserlizer.data},
                                         "Restaurant with this all data."), status=status.HTTP_200_OK)

我的JSON响应是

   "article_option":{  },
        "order_article":{  
           "order":{  
              "restaurant":{  },
              "tableid":12,
              "orderid":1,
              "total_amount":"0.00"
           },
           "article":{  
              "id":1,
              "category":{  },
              "ingredient":[  ],
              "articleoptionnames":{  },
              "restaurant":{  },
              "articlename":"Article1",
              "price":"1.90",
              "pickuptax":6,
              "dineintax":21,
              "description":"This is a tekst field with more information about the product",
              "image":"/media/Article/c1.264f3b28_sxcPiqi.png"
           }
        },

虽然我希望这些“ article_option”作为Article {article_option1,article_option2}之类的文章的子代,但它会为每个新的article选项创建新对象。

1 个答案:

答案 0 :(得分:1)

如果我对您的理解正确,那么您想返回OrderArticle的表示形式,其中有ArticleOption个对象作为其子代。这意味着您应该实例化视图中的ArticlesSerializer,但还要修改ArticlesSerializer,以使其包含所有相关的article_options作为列表(使用source属性)。类似于以下内容:

class ArticlesOptionSerializer(serializers.ModelSerializer):
    article_option = ListCategoriesSerializer(read_only=True)

    class Meta:
        model = OrderArticleOptions
        fields = ['article_option', 'order_article', 'quantity', 'price']


class ArticlesSerializer(serializers.ModelSerializer):
    order = OrderSerializer(read_only=True)
    article = ListArticleSerializer(read_only=True)
    article_options = ArticlesOptionSerializer(read_only=True, source='orderarticleoptions_set', many=True)

    class Meta:
        model = OrderArticle
        fields = ['order', 'article', 'article_options']

然后,在您的视图中,应使用适当的ArticlesSerializer对象实例化OrderArticle

class OrderedArticles(APIView):
    def get(self, request, restid):
        order_article = OrderArticle.objects.get(pk=1) # get pk/id from request
        serializer = ArticlesSerializer(order_article)
        return Response(serializer.data, status=status.HTTP_200_OK)