Getting the SQL from a Django QuerySet [duplicate]
You print the queryset’s query attribute. >>> queryset = MyModel.objects.all() >>> print(queryset.query) SELECT “myapp_mymodel”.”id”, … FROM “myapp_mymodel”
You print the queryset’s query attribute. >>> queryset = MyModel.objects.all() >>> print(queryset.query) SELECT “myapp_mymodel”.”id”, … FROM “myapp_mymodel”
From the Django documentation: Blog.objects.filter(pk__in=[1, 4, 7])
Such lookups are implemented in django.views.generic.date_based as follows: {‘date_time_field__range’: (datetime.datetime.combine(date, datetime.time.min), datetime.datetime.combine(date, datetime.time.max))} Because it is quite verbose there are plans to improve the syntax using __date operator. Check “#9596 Comparing a DateTimeField to a date is too hard” for more details.
With Django 1.8 and above you can now pass an expression to your aggregate: from django.db.models import F Task.objects.aggregate(total=Sum(F(‘progress’) * F(‘estimated_days’)))[‘total’] Constants are also available, and everything is combinable: from django.db.models import Value Task.objects.aggregate(total=Sum(‘progress’) / Value(10))[‘total’]
There is Q objects that allow to complex lookups. Example: from django.db.models import Q Item.objects.filter(Q(creator=owner) | Q(moderated=False))
Summary: One option is, as suggested by jpic and sgallen in the comments, to add .filter() for each category. Each additional filter adds more joins, which should not be a problem for small set of categories. There is the aggregation approach. This query would be shorter and perhaps quicker for a large set of categories. … Read more
Use Sample.objects.filter(date__range=[“2011-01-01”, “2011-01-31″]) Or if you are just trying to filter month wise: Sample.objects.filter(date__year=”2011″, date__month=”01”) Edit As Bernhard Vallant said, if you want a queryset which excludes the specified range ends you should consider his solution, which utilizes gt/lt (greater-than/less-than).
Concatenating the querysets into a list is the simplest approach. If the database will be hit for all querysets anyway (e.g. because the result needs to be sorted), this won’t add further cost. from itertools import chain result_list = list(chain(page_list, article_list, post_list)) Using itertools.chain is faster than looping each list and appending elements one by … Read more