django.core.exceptions.FieldError:尝试选择属性字段时无法将关键字'duration'解析为字段



关于这个特定的错误有很多问题,但没有一个是由于试图从序列化程序中选择属性字段而引起的,下面是我的代码

# seriliazer.py
class ProjectActivitySerializer(serializers.ModelSerializer):
is_running = serializers.ReadOnlyField()
duration = serializers.ReadOnlyField() # i am trying to select this particular field to perform some calculation

class Meta:
model = ProjectActivity
fields = '__all__'

class ProjectActivity(models.Model):
id = models.AutoField(primary_key=True)
description = models.TextField(blank=False, null=False, 
max_length=400, default="")
project = models.ForeignKey(to=Project, 
on_delete=models.CASCADE)
user = models.ForeignKey(to=Employee, on_delete=models.CASCADE)
start_time = models.DateTimeField(auto_now_add=True)
end_time = models.DateTimeField(blank=True, null=True)
@property
def duration(self):
"""
get the duration of the activity
Returns:
timedelta: duration of the activity
"""
if self.is_running:
sec = datetime.now(timezone.utc) - self.start_time
return str(timedelta(seconds=round(sec.total_seconds())))
else:
sec = self.end_time - self.start_time
return str(timedelta(seconds=round(sec.total_seconds())))

class GetTotalProjectActivityTime(ListAPIView):
"""

"""
serializer_class = ProjectActivitySerializer
permission_classes = (IsAuthenticated, IsOwner|IsAdminUser) # protect the endpoint


def get_queryset(self):
return ProjectActivity.objects.filter(user=self.kwargs['user'], project__id=self.kwargs['project']).values('duration')

Just a background to my problem here: i have the below response
[
{
"id": 1,
"is_running": true,
"duration": "2 days, 5:43:26",
"description": "worked on developing dashboard endpoint",
"start_time": "2021-12-22T11:40:49.452935Z",
"end_time": null,
"project": 1,
"user": 1
}
]

我想对持续时间进行计算,但持续时间字段不是我的模型字段的一部分,而是一个公正的属性。持续时间值是从模型的持续时间属性中获得的,我想从响应中计算总持续时间。

现在我发现运行计算很困难

首先将duration属性更改为使用cached_property,这样做可以创建具有相同名称的注释,并且在对象上设置注释值时不会发生冲突。

from django.utils.functional import cached_property
from django.utils.timezone import now
class ProjectActivity(models.Model):
@cached_property
def duration(self):
return (self.end_time or now()) - self.start_time

现在,我们可以使用以下用duration注释查询集

from django.db.models import F
from django.db.models.functions import Coalesce, Now
queryset = ProjectActivity.objects.annotate(
end_or_now=Coalesce('end_time', Now()))
).annotate(
duration=F('end_or_now') - F('start_time')
)

该注释可以用于进一步的注释、过滤器、聚合等

from django.db.models import Sum
queryset.aggregate(total_duration=Sum('duration'))

最新更新