# Here is my models
這是我設計的 CustmerBuySell 模型資料庫。
class CustomerBuySell(models.Model):
customer = models.ForeignKey(CustomerAdd, on_delete=models.CASCADE)
customer_buy_sell_debit = models.DecimalField(max_digits=10, decimal_places=2, default=0.00)
customer_buy_sell_credit = models.DecimalField(max_digits=10, decimal_places=2, default=0.00)
description = models.CharField(max_length=250, blank=True)
date = models.DateField()
sms = models.BooleanField(default=False)
picture = models.ImageField(upload_to='customer_buy_sell_pics', default='images.png')
created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)
updated_at = models.DateTimeField(auto_now=True, blank=True, null=True)
def __str__(self):
return self.customer.customer_name
class Meta:
verbose_name = "Customer BuySell"
verbose_name_plural = "Customer BuySell"
# Here, is my View.
這是我使用過的基于類的 APIView。并嘗試在此視圖中使用聚合查詢。
class DailyCustomerBuySellAPIView(APIView):
def get(self, request):
customer_buy_sell = CustomerBuySell.objects.extra(select={'day': 'date( date )'}).values('day').order_by(
'date__date').annotate(available=Count('date__date'))
serializer = CustomerBuySellSerializer(customer_buy_sell, many=True)
return Response({"customer_buy_sell": serializer.data})
# And, finally here are my Serializers
我不知道有什么問題!請幫我。
class CustomerBuySellSerializer(serializers.ModelSerializer):
# customer = CustomerAddSerializer()
class Meta:
model = CustomerBuySell
fields = '__all__'
def to_representation(self, instance):
representation = super(CustomerBuySellSerializer, self).to_representation(instance)
if instance.customer is not None:
customer_name = instance.customer.customer_name
previous_due = instance.customer.previous_due
representation['custo`enter code here`mer_name'] = customer_name
representation['previous_due'] = previous_due
return representation
uj5u.com熱心網友回復:
你的方法有很多問題。讓我一一提及:
- 首先從您的 APIVIew 中洗掉 date__date
前:
customer_buy_sell = CustomerBuySell.objects.extra(select={'day': 'date( date )'}).values('day').order_by(
'date__date').annotate(available=Count('date__date'))
相反,將其寫為:
from django.db.models.functions import Extract
customer_buy_sell = CustomerBuySell.objects.annotate(day=Extract('date','day')).values('day').order_by('day')
如果您需要計算天數,那么您可以嘗試
customer_buy_sell_count = customer_buy_sell.count()
您做錯的另一件事是您將 dict 傳遞給序列化程式,因為您已經在使用
values它回傳一個日期字典而不是物件,CustomerBuySell因此您不需要將它傳遞給序列化程式,否則您必須根據需要進行操作。在
CustomerBuySellSerializer您使用模型序列化程式時__all__,您正在傳遞一個不屬于它的額外欄位日。
所以簡而言之,你的 Django 和 Django Rest Framework 存在很多語法問題。解決這些問題的好方法是與經驗豐富的程式員一起設定,以便他可以改進代碼流。稍后您可以專注于邏輯。
uj5u.com熱心網友回復:
我想這只是一個錯字:Change date__date to date
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/429434.html
標籤:django 日期 django-rest-framework
上一篇:帶有日期的Pandas資料操作
