使用 postgres 的 2 个模型的 Django queryset NOT INTERSECT
Django queryset NOT INTERSECT for 2 models using postgres
我有一个 Django 应用程序,我想找出 2017 年 12 月 5 日未出勤的员工。我正试图找出一个查询集来完成这个。
以下是我试图完成的模型、记录和结果的详细信息。
我有 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",
"id":4, "fullname":"selena gomez"}
Attendance
{"id":1, "employee": 1,"activity_type": 1, timestamp: "2017-12-05 09:08",
"id":2, "employee": 2,"activity_type": 1, timestamp: "2017-12-05 10:13",
"id":3, "employee": 2,"activity_type": 2, timestamp: "2017-12-05 15:13",
"id":4, "employee": 2,"activity_type": 1, timestamp: "2017-12-05 19:13",
"id":5, "employee": 3,"activity_type": 1, timestamp: "2017-12-06 08:08"}
这是我想要完成的预期输出:
对于日期 2017-12-05,该员工没有出勤(意味着 2017-12-05 的出勤记录中没有记录)
{"id":3, "fullname":"taylor swift",
"id":4, "fullname":"selena gomez"}
列出特定日期 2017-12-05 未出席的员工的查询集是什么?我相信它与员工相交并且不做。
您可以通过一个简单的 exclude()
查询来做到这一点:
from datetime import date
today = date.today()
Employee.objects.exclude(attendance__timestamp__date=today)
这将为您提供该日期没有出勤记录的所有员工。
有关如何创建查找的说明,请参阅 this section of the documentation。
我有一个 Django 应用程序,我想找出 2017 年 12 月 5 日未出勤的员工。我正试图找出一个查询集来完成这个。
以下是我试图完成的模型、记录和结果的详细信息。
我有 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",
"id":4, "fullname":"selena gomez"}
Attendance
{"id":1, "employee": 1,"activity_type": 1, timestamp: "2017-12-05 09:08",
"id":2, "employee": 2,"activity_type": 1, timestamp: "2017-12-05 10:13",
"id":3, "employee": 2,"activity_type": 2, timestamp: "2017-12-05 15:13",
"id":4, "employee": 2,"activity_type": 1, timestamp: "2017-12-05 19:13",
"id":5, "employee": 3,"activity_type": 1, timestamp: "2017-12-06 08:08"}
这是我想要完成的预期输出:
对于日期 2017-12-05,该员工没有出勤(意味着 2017-12-05 的出勤记录中没有记录)
{"id":3, "fullname":"taylor swift",
"id":4, "fullname":"selena gomez"}
列出特定日期 2017-12-05 未出席的员工的查询集是什么?我相信它与员工相交并且不做。
您可以通过一个简单的 exclude()
查询来做到这一点:
from datetime import date
today = date.today()
Employee.objects.exclude(attendance__timestamp__date=today)
这将为您提供该日期没有出勤记录的所有员工。
有关如何创建查找的说明,请参阅 this section of the documentation。