简体   繁体   中英

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. 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:

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)

{"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 ? I believe its an intersect and doing a NOT with the employee.

You can do this with a simple exclude() query:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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