如何在 django 中计算某些 if 条件的字段平均值?
Posted
技术标签:
【中文标题】如何在 django 中计算某些 if 条件的字段平均值?【英文标题】:How to calculate average of fields on some if conditions in django? 【发布时间】:2021-11-20 19:06:15 【问题描述】:我在 Django 上工作,我有两个模型 Gigs 和 Orders,我正在计算每个 gig 的订单的平均完成时间。
在 订单 模型中,我有两个字段 订单开始时间(每当卖家接受订单时我都会发送)和 订单完成时间 (我在卖家发货时发送)订单。
但我只想计算isCompleted = True
Models.py
class Orders(models.Model):
buyer = models.ForeignKey(User,default=None, on_delete=models.CASCADE,related_name='buyer_id')
seller = models.ForeignKey(User,default=None, on_delete=models.CASCADE,related_name='seller_id')
item = models.ForeignKey(Gigs,default=None, on_delete=models.CASCADE,related_name='gig')
payment_method= models.CharField(max_length=10)
address = models.CharField(max_length=255)
mobile = models.CharField(max_length=13,default=None)
quantity = models.SmallIntegerField(default=1)
status = models.CharField(max_length=13,default='new order')
orderStartTime = models.DateTimeField(default=timezone.now)
orderCompletedTime = models.DateTimeField(default=timezone.now)
isCompleted = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
class Gigs(models.Model):
title = models.CharField(max_length=255)
category = models.ForeignKey(Categories , on_delete=models.CASCADE)
images = models.ImageField(blank=True, null = True, upload_to= upload_path)
price = models.DecimalField(max_digits=6, decimal_places=2)
details = models.TextField()
seller = models.ForeignKey(User,default=None, on_delete=models.CASCADE)
@property
def average_completionTime(self):
if getattr(self, '_average_completionTime', None):
return self._average_completionTime
return self.gig.aggregate(Avg(F('orderCompletedTime') - F('orderStartTime')))
Views.py
class RetrieveGigsAPI(GenericAPIView, RetrieveModelMixin):
def get_queryset(self):
return Gigs.objects.annotate(
_average_completionTime=Avg(
ExpressionWrapper(F('gig__orderCompletedTime') - F('gig__orderStartTime'), output_field=DurationField())
)
)
serializer_class = GigsSerializerWithAvgTime
permission_classes = (AllowAny,)
def get(self, request , *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
Serializers.py
class GigsSerializerWithAvgTime(serializers.ModelSerializer):
average_completionTime = serializers.SerializerMethodField()
def get_average_completionTime(self, obj):
return obj.average_completionTime
class Meta:
model = Gigs
fields = ['id','title','category','price','details','seller','images','average_completionTime']
请告诉我如何才能获得那些 iscompleted 为 True 的订单完成时间的平均值
【问题讨论】:
【参考方案1】:您可以为Avg
指定一个过滤器,以仅聚合基于isCompleted
的已完成订单,如下所示:
class RetrieveGigsAPI(GenericAPIView, RetrieveModelMixin):
def get_queryset(self):
return Gigs.objects.annotate(
_average_completionTime=Avg(
ExpressionWrapper(F('gig__orderCompletedTime') - F('gig__orderStartTime'), output_field=DurationField()),
filter=Q(gig__isCompleted=True),
# ^^^ Add this
)
)
【讨论】:
【参考方案2】: if isCompleted:
foo = Gigs.objects.annotate(_average_completionTime=Avg(
ExpressionWrapper(F('gig__orderCompletedTime') F('gig__orderStartTime'), output_field=DurationField())
)
)
return foo
【讨论】:
以上是关于如何在 django 中计算某些 if 条件的字段平均值?的主要内容,如果未能解决你的问题,请参考以下文章
Django-create 过滤器基于使用 Q 对象和 if elif 条件的每个字段