简体   繁体   English

使用postgres的2个模型的Django queryset NOT INTERSECT

[英]Django queryset NOT INTERSECT for 2 models using postgres

I have a Django app, and I am trying to find out Employee that was NOT in Attendance 2017-12-05. 我有一个Django应用,并且我试图找出不在出勤2017-12-05中的员工。 I am trying to find out a queryset to accomplish this. 我试图找出一个查询集来完成此任务。

The following are the details of the model, records, and the outcome I am trying to accomplish. 以下是我想要完成的模型,记录和结果的详细信息。

I have 2 models: 我有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)

Assuming I have the records below: 假设我有以下记录:

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"}

This is the intended output I am trying to accomplish: 这是我要完成的预期输出:

For the date 2017-12-05, this employee was not in attendance (meaning there was no record in Attendance for 2017-12-05) 在2017-12-05日期中,该员工没有出席(意味着2017-12-05中的出勤记录没有记录)

{"id":3, "fullname":"taylor swift",
"id":4, "fullname":"selena gomez"}

What is the queryset to list out the employee that is not in attendance on a particular date 2017-12-05 ? 列出在2017-12-05特定日期未出席的员工的查询集是什么? I believe its an intersect and doing a NOT with the employee. 我相信这是一个交叉点,并且与员工不做任何事情。

You can do this with a simple exclude() query: 您可以使用简单的exclude()查询来做到这一点:

from datetime import date

today = date.today()

Employee.objects.exclude(attendance__timestamp__date=today)

This will give you all the employees where there was no attendance recorded for that date. 这将为您提供该日期没有出勤记录的所有员工。

See this section of the documentation for explanation of how to create the lookup. 有关如何创建查找的说明,请参见文档的本部分

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM