python 订单查询按DRF中的价格总和设置

fykwrbwg  于 2023-11-15  发布在  Python
关注(0)|答案(1)|浏览(114)

我使用OrderingFilter,我有比萨饼模型连接到比萨饼模型通过多对多字段,当我订购的desc或asc我得到的不是预期的结果,如何可以得到queryset订购的价格或价格的第一个数字的总和
models.py

class Categorie(models.Model):
    name = models.CharField(max_length=60, default=[0])

    def __str__(self) -> str:
        return self.name

class PizzaPrice(models.Model):
    price = models.DecimalField(max_digits=8, decimal_places=2)

    def __str__(self) -> str:
        return str(self.price)
    
    class Meta:
        ordering = ['price']

class PizzaSize(models.Model):
    size = models.IntegerField()

    class Meta:
        ordering = ['size']

    def __str__(self) -> str:
        return str(self.size)

class Pizza(models.Model):
    name = models.CharField(max_length=60)
    imageUrl = models.CharField(max_length=150)
    category = models.ForeignKey(Categorie, default=1, on_delete=models.CASCADE)
    rating = models.IntegerField(choices=PIZZA_RATING, default=1)
    sizes = models.ManyToManyField(PizzaSize, blank=True, default=[0])
    prices = models.ManyToManyField(PizzaPrice, blank=True, default=[0])

    def __str__(self) -> str:
        return self.name

字符串
serializer.py

class PizzaSerializer(serializers.ModelSerializer):
    category = serializers.CharField(source='category.name')
    sizes = serializers.SlugRelatedField(many=True, read_only=True, slug_field='size')
    prices = serializers.SlugRelatedField(many=True, read_only=True, slug_field='price')

    class Meta:
        model = Pizza
        fields = '__all__'


views.py

class PizzasList(generics.ListAPIView):
    queryset = Pizza.objects.all()
    serializer_class = PizzaSerializer
    pagination_class = PageNumberPagination
    filter_backends = [DjangoFilterBackend, OrderingFilter]

    filterset_fields = ['category']
    ordering_fields = ['rating', 'name', 'prices']


example of result: ordering by prices
我尝试了很多选择,但没有帮助
我开始学习Django不是很久,我知道的不多,我希望你能帮助这个问题,谢谢你的关注
want to get queryset order by total sum of prices or first number in prices

j8ag8udp

j8ag8udp1#

要按每个披萨的价格总和对查询集进行排序,您可以使用Django的Sum函数沿着查询集中的annotate方法。下面是对PizzasList视图的修改示例:

from django.db.models import Sum

class PizzasList(generics.ListAPIView):
    queryset = Pizza.objects.annotate(total_price=Sum('prices__price'))
    serializer_class = PizzaSerializer
    pagination_class = PageNumberPagination
    filter_backends = [DjangoFilterBackend, OrderingFilter]

    filterset_fields = ['category']
    ordering_fields = ['rating', 'name', 'total_price']

字符串
此修改使用annotate为查询集中的每个比萨饼添加一个新字段total_price,表示与该比萨饼关联的价格总和。然后,您可以在ordering_fields中按total_price进行订购。请注意,这假设您希望按升序订购。如果您希望按降序订购,则可以使用-total_price

相关问题