【发布时间】:2022-01-25 05:27:33
【问题描述】:
关于这个特定错误有很多问题,但没有一个是由于尝试从序列化程序中选择属性字段引起的,下面是我的代码
# 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
}
]
我想对持续时间进行计算,但持续时间字段不是我的模型字段的一部分,而是一个公正的属性。持续时间值是从模型的持续时间属性中获取的,我想从响应中计算总持续时间。
现在我发现运行计算很困难
【问题讨论】:
-
要在
queryset中使用它,您必须使用F()annotationsannotate它。 -
你想做什么?
-
显示 ProjectActivity 模型?
-
@IainShelvington 我已经做到了。
-
@shivankgtm 我想总结所有的持续时间值
标签: python django django-rest-framework