11👍
✅
Performing statement in a single query is no guarantee to improve performance, this is easy to understand if you try to write an agnostic RDBMS brand SQL single sentence for yours requirements. Also, you lost in readability.
In my opinion, you can see and elegant solution in this approach:
- Get last
Expo
by date . - Do a simple filter query.
For your code:
max_year = Expo.objects.latest('date').date.year
expos = Expo.objects.filter(date__year=max_year)
Remember you can cache max_year, also create a DESC
index over date
can helps.
2👍
Here is how you can do something using a combination of Annotation and F object
To filter on Max date:
ModelClass.objects.annotate(max_date=Max('pubdate')).filter(pubdate=F('max_date'))
To filter on the year of Max date:
max_date = ModelClass.objects.latest("pubdate").pubdate
published_objs = ModelClass.objects.filter(pubdate__year=max_date.year)
There does not seem to be a way to filter on Max(date.year) in a single query. And as mentioned by @danihp, even a single query is not a guarantee of performance.
- How to access the meta attributes of a superclass in Python?
- Python-social-auth not getting correct Google OAuth2 details
- Push notifications with django and GCM
- Django: Signal on queryset.update
- Django v1.6 debug-toolbar Middleware Error No .rsplit()
2👍
Throoze try this…
queryset=Expo.objects.annotate(max_date=Max('date'))
queryset1=queryset.values().filter(date__gte=F('max_date'))
- JSON data convert to the django model
- Django ORM for desktop application
- How to handle Python multiprocessing database concurrency, specifically with django?
- How can I create a partial search filter in Django REST framework?
- Exclude an app from Django migrations
Source:stackexchange.com