Created
October 21, 2011 19:34
-
-
Save ryanpitts/1304725 to your computer and use it in GitHub Desktop.
GROUP BY and Select MAX from each group in Django, 2 queries
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
given a Model with: | |
category = models.CharField(max_length=32, choices=CATEGORY_CHOICES) | |
pubdate = models.DateTimeField(default=datetime.now) | |
<other fields> | |
Fetch the item from each category with the latest pubdate. | |
''' | |
model_max_set = Model.objects.values('category').annotate(max_pubdate=Max('pubdate')).order_by() | |
q_statement = Q() | |
for pair in model_max_set: | |
q_statement |= (Q(category__exact=pair['category']) & Q(pubdate=pair['max_pubdate'])) | |
model_set = Model.objects.filter(q_statement) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Any Idea...???
this is my model, i want output like this
one day user login&logout multiple times but i need day1 user login,logout time again day 2 same user login, logout time
i tried with this but not working
output like this:
agent1 login 2021-10-20 17:09:50.957295 logout 2021-10-21 21:45:54.955938
agent 3 login 2021-10-20 12:57:57.923346 logout 2021-10-20 12:58:20.246713
day 2
agent1 login 2021-10-21 12:58:40.147530 logout 2021-10-21 12:59:02.528687
agent 3 login 2021-10-21 21:45:54.858950 logout 2021-10-21 14:01:22.189149