Rajat Jog
Rajat Jog

Reputation: 317

Want to perform left join in django

Say I've 2 models

Model Users:
       Name:
       Id:

And attendance

Model Attendance:
   user: foreign_key(User)
   present: [present if login else nothing recorded]
   Date:


users = User.objects.all()
todays_present = Attendance.objects.filter(date=today)

Now for instance Users = 10 todays_present = 7

I want to find which three users are not in todays_present.

Upvotes: 1

Views: 37

Answers (3)

Rajat Jog
Rajat Jog

Reputation: 317

first of thanks to these two guys @willem and @AKX, who made me think in correct direction.

What I did is, first get all present employees with

presents = Attendance.objects.filter(date=today)

then exclude them from all users like:

absent = User.objects.exclude(attendance_set__in=presents)

This worded How I wanted it be...

Upvotes: 0

AKX
AKX

Reputation: 169051

This should get you the actual user objects not attendant for today (though Willem Van Onsem's solution is simpler).

You may need to adjust 'attendance_set' depending on your actual model related name.

users_not_present_today = User.objects.annotate(
  today_attendance_count=Count('attendance_set', filter=Q(present=True, date=today)
).filter(today_attendance_count=0)

Upvotes: 2

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476709

You can work with .exclude(…) [Django-doc] with:

User.objects.exclude(attendance__date=today)

This will retrieve all users for which no Attendance can be found where the date field is equal to today.

Upvotes: 3

Related Questions