DRF-API列表视图-具有最近子项的父项

时间:2019-01-04 18:57:32

标签: python django model django-rest-framework serializer

我正在尝试为Django rest API创建自定义列表视图。此列表应包含其最新价格(子项)的所有文章(父项)。我的Django模型如下:

class Article(models.Model):
    id = models.AutoField(primary_key=True, verbose_name="Article ID")
    name = models.CharField(max_length=250, verbose_name="Name")

class Price(models.Model):
    article = models.ForeignKey(Article, on_delete=models.CASCADE, verbose_name="Article", related_name="prices")
    price = models.DecimalField(max_digits=6, decimal_places=2, verbose_name="Price")

具有以下序列化器:

class PriceSerializer(serializers.ModelSerializer):

    class Meta:
        model = Price
        fields = '__all__'

class ArticleSerializer(serializers.ModelSerializer):

    prices = PriceSerializer(many=True)

    class Meta:
        model = Article
        fields = '__all__'

现在,我想创建一个@list_route()通过GET请求访问列表:

class ArticleViewSet(viewsets.ModelViewSet):

    queryset = Article.objects.all().order_by('id')
    serializer_class = ArticleSerializer

    @list_route(methods=['GET'])
    def recentprices(self, request, *args, **kwargs):

        ?...?



class PriceViewSet(viewsets.ModelViewSet):

    queryset = Price.objects.all()
    serializer_class = PriceSerializer

有人可以帮我填补点吗?

0 个答案:

没有答案