Reputation: 5800
I have the following model:
class Attendance(TimeStamped):
employee_id = models.CharField(max_length=10)
punch = models.DateTimeField()
The employee punches twice everyday, once to get in and once to log out.
I want to come up with a QuerySet so that I get only the PUNCH INs of the employee. I tried to use distinct()
but can't get it to work.
So if an employee goes to office for two days I will have four rows in the model. But I want to only get two rows; only the first result of each date.
How can I do this?
Upvotes: 2
Views: 306
Reputation: 9235
If you really want to distinguish between login and logout then, you need to consider refactoring your models a bit like this..
class Attendance (TimeStamped):
..........................
punch_in = models.BooleanField(default=True)
punch_out = models.BooleanField(default=False)
def save(self, *args, **kwargs):
try:
login = Attendance.objects.get(modified=self.modified)
self.punch_out = True
self.punch_in = False
except Attendance.DoesNotExist:
pass
return super(Attendance, self).save(*args, **kwargs)
Then you could do queries with,
Attendance.objects.filter(modified=some_date, punch_in=True)
Assuming the instances aren't meant to be modified. Or you would have to utilise the datetime.combine() , which would make the code more ugly.
I'd recommend to use models.DateField() for the modified field.The above code is under the assumption of the same.
Another option is to add a field similar to created field but of the type models.DateField() which is redundant.
Hope this would work for you..
Upvotes: 1