【发布时间】:2018-05-23 11:37:08
【问题描述】:
我正在尝试查找查询以获取特定日期的最新出勤列表,其中包含已签到的唯一员工 (CHECKIN = 1)
下面是我的模型、记录和我想要完成的任务。
我的模型有 2 个模型:
class Employee(models.Model):
fullname = models.CharField(max_length=30, blank=False)
class Attendance(models.Model):
CHECKIN = 1
CHECKOUT = 2
ATTENDANCE_TYPE_CHOICES = (
(CHECKIN, "Check In"),
(CHECKOUT, "Check Out"),
)
employee = models.ForeignKey(Employee)
activity_type = models.IntegerField(choices = ATTENDANCE_TYPE_CHOICES, default=CHECKIN)
timestamp = models.DateTimeField(auto_now_add=True)
假设我有以下记录:
Employee
{"id":1, "employee":"michael jackson",
"id":2, "fullname":"mariah carey",
"id":3, "fullname":"taylor swift"}
Attendance
{"id":1, "employee": 1,"activity_type": 1, timestamp: "2017-12-05 09:08", -interested in this for the activity type (1 for CHECKIN) and the date 2017-12-05, last of that employee id for that day
"id":2, "employee": 2,"activity_type": 1, timestamp: "2017-12-05 10:13",
"id":3, "employee": 3,"activity_type": 1, timestamp: "2017-12-05 11:30",
"id":4, "employee": 2,"activity_type": 2, timestamp: "2017-12-05 15:13",
"id":5, "employee": 3,"activity_type": 2, timestamp: "2017-12-05 18:30",
"id":6, "employee": 2,"activity_type": 1, timestamp: "2017-12-05 19:13", -interested in this for the activity type (1 for CHECKIN) and the date 2017-12-05, last of that employee id for that day
"id":7, "employee": 3,"activity_type": 1, timestamp: "2017-12-05 20:30", -interested in this for the activity type (1 for CHECKIN) and the date 2017-12-05, last of that employee id for that day
"id":8, "employee": 1,"activity_type": 2, timestamp: "2017-12-06 08:08"}
我很感兴趣,因此它仅根据 CHECKIN 的活动类型 1 和日期 2017-12-05 输出这 2 条记录,并且员工 ID 必须是唯一且最新的:
{"id":1, "employee": 1,"activity_type": 1, timestamp: "2017-12-05 09:08",
"id":6, "employee": 2,"activity_type": 1, timestamp: "2017-12-05 19:13"
"id":7, "employee": 3,"activity_type": 1, timestamp: "2017-12-05 20:30"}
我正在使用 Postgres 9.4
如何使用 Django 查询集产生预期的结果?
【问题讨论】:
标签: python django postgresql distinct django-queryset