Axil
Axil

Reputation: 3311

Django Queryset get list for the day of a particular type, unique foreignkey id using Postgres database

I am trying to find a query to get a list of latest attendance for a particular day, with unique employee that has checked in (CHECKIN = 1)

Below is my model, records and what I am trying to accomplish.

My model has 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"}

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

I am interest so that it output this 2 record only based on the activity type 1 for CHECKIN and for the date 2017-12-05 and that employee id must be unique and latest:

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

I am using Postgres 9.4

How can I produce the intended result with Django queryset ?

Upvotes: 0

Views: 192

Answers (1)

Satendra
Satendra

Reputation: 6865

Filter attendance by activity_type, order by employee_id and -timestamp then use distinct on employee_id

Attendance.objects.filter(activity_type=Attendance.CHECKIN).order_by('employee_id','-timestamp').distinct('employee_id')

Upvotes: 1

Related Questions