gpt4 book ai didi

python - 如何在同一api内的django rest框架中获取聚合

转载 作者:太空宇宙 更新时间:2023-11-04 04:32:10 25 4
gpt4 key购买 nike

这是我的模型.py

from __future__ import unicode_literals
from django.db import models

class User(models.Model):
name = models.CharField(max_length=200)
company_name = models.ForeignKey('Company',on_delete=models.CASCADE,related_name='user')

def __str__(self):
return self.name

class Company(models.Model):
name = models.CharField(max_length=200)
phone_number = models.IntegerField(null=True,blank=True)

def __str__(self):
return self.name

class Catalog(models.Model):
name = models.CharField(max_length=200)
no_of_pcs = models.IntegerField(null=True,blank=True)
per_piece_price = models.DecimalField(null=True,blank=True,max_digits=10,decimal_places=2)
company_name = models.ForeignKey(Company,on_delete=models.CASCADE,related_name='catalog')

def __str__(self):
return self.name

这是我的serializers.py

from rest_framework import serializers
from .models import *
from django.db.models import Sum,Avg,Max,Min,Count,F,Q

class CatalogSerializer(serializers.HyperlinkedModelSerializer):
dynamic_data = serializers.SerializerMethodField()
class Meta:
model = Catalog
fields = '__all__'

def get_dynamic_data(self, obj):
totalpieces = Catalog.objects.all().aggregate(total_pieces=Count('no_of_pcs'))
totalprice = Catalog.objects.all().aggregate(total_price=Sum('per_piece_price'))
print(totalpieces["total_pieces"],totalprice["total_price"])
return totalpieces["total_pieces"],totalprice["total_price"]


class UserSerializer(serializers.ModelSerializer):
# name = serializers.StringRelatedField()
company_name = serializers.CharField()
class Meta:
model = User
fields = '__all__'

class CatalogData(serializers.ModelSerializer):
class Meta:
model = Catalog
fields = ('name', 'no_of_pcs', 'per_piece_price')


class CompanySerializer(serializers.ModelSerializer):
# catalog_details = serializers.SerializerMethodField()
# name = serializers.StringRelatedField()
catalog = CatalogData(many=True)
user = UserSerializer(many=True)
class Meta:
model = Company
fields = ('name', 'phone_number', 'catalog','user')

这是我的views.py

from __future__ import unicode_literals
from django.http import HttpResponse
from .models import *
import json
from django.http import JsonResponse, HttpResponse
from .serializers import *
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework import viewsets


class CatalogView(viewsets.ModelViewSet):
queryset = Catalog.objects.select_related('company_name')
serializer_class = CatalogSerializer


class CompanyView(viewsets.ModelViewSet):
queryset = Company.objects.all()
serializer_class = CompanySerializer

class UserView(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer

我正在获取这样的 api..

[
{
"url": "http://127.0.0.1:8000/catalogs/1/",
"dynamic_data": [
3,
471118.0
],
"name": "sarees",
"no_of_pcs": 23,
"per_piece_price": "33333.00",
"company_name": "http://127.0.0.1:8000/companies/1/"
}
]

这里的动态数据3是total no of pieces意思是aggregate Count而在动态数据中471118.0是总价表示聚合Sum

但我期待不同格式的 api

像这样:

[
{
"url": "http://127.0.0.1:8000/catalogs/1/",
"total_pieces":3,
"total_price": 471118.0
"name": "sarees",
"no_of_pcs": 23,
"per_piece_price": "33333.00",
"company_name": "http://127.0.0.1:8000/companies/1/"
}
]

我想在同一个 api 中获得 total_pieces 和 total_price。

谢谢,,

最佳答案

在一个函数中你返回两个值,所以 django 不会把它分开并将它作为一个列表传递,如果你想要不同的键值对使用这个

class CatalogSerializer(serializers.HyperlinkedModelSerializer):
total_pieces = serializers.SerializerMethodField()
total_price = serializers.SerializerMethodField()
class Meta:
model = Catalog
fields = '__all__'

def get_total_pieces(self, obj):
totalpieces = Catalog.objects.all().aggregate(total_pieces=Count('no_of_pcs'))
return totalpieces["total_pieces"]
def get_total_price(self, obj):
totalprice = Catalog.objects.all().aggregate(total_price=Sum('per_piece_price'))
return totalprice["total_price"]

关于python - 如何在同一api内的django rest框架中获取聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52473960/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com