我想每天汇总每个人的所有出勤记录,在我目前的解决方案中,我需要获取所有记录,然后使用for循环,有没有更好的方法来获取查询集,如下所示:
class AttendanceRecord(models.Model):
user_id = models.IntegerField()
device_id = models.IntegerField()
f_time = models.DateTimeField(auto_created=True)
# How to group record by user and get a queryset like the following?
[
[
{'user_id': 1, 'device_id': 1, 'f_time': '2020-11-11 8:00:00'},
{'user_id': 1, 'device_id': 1, 'f_time': '2020-11-11 18:00:00'}
],
[
{'user_id': 2, 'device_id': 2, 'f_time': '2020-11-11 8:00:00'},
{'user_id': 2, 'device_id': 2, 'f_time': '2020-11-11 18:00:00'}
],
]
# or like this
[
{user_id1: [
{'device_id': 1, 'f_time': '2020-11-11 8:00:00'},
{'device_id': 1, 'f_time': '2020-11-11 18:00:00'}
]},
{user_id2: [
{'device_id': 2, 'f_time': '2020-11-11 8:00:00'},
{'device_id': 2, 'f_time': '2020-11-11 18:00:00'}
]},
]发布于 2020-12-11 16:02:51
您需要的数据集可以使用prefetch_related高效地构建。
userinfo = UserInfo.objects.all().prefetch_related("attendancerecord_set")
for ui in userinfo:
for ar in ui.addendancerecord_set.all():
print(ar)在模板代码中
{% for ui in userinfo %}
{% for ar in ui.addendancerecord_set.all %}
f_Device_id:{{ ar.f_Device_id }} f_time:{{ ar.f_time }}
{% endfor %}
{% endfor %}https://stackoverflow.com/questions/65246477
复制相似问题