Django query execute behaviour - django

I have written this in django
a = Model.objects.all()
Will this query execute immediately or not?
When will this query fetch the request from the db?

In Django the Querysets are lazy i.e. when you create a queryset, it will involve any database activity,unless the queryset is evaluated.Read this Documentation for more in depth information.

Related

Django Get and Filter

I have a design question on django.
Can someone explain to me why the Django ORM 'get' doesn't return a queryset?
To the best of my understanding, a queryset should/is the result of a db query. With that logic, isn't a get query a queryset?
Also, from my research towards this question, I found out the get query calls the model manager while the queryset doesn't.
Is there a reasoning behind all of this?
From django documentation queryset api reference
get() raises MultipleObjectsReturned if more than one object was found. The MultipleObjectsReturned exception is an attribute of the model class.
While filter returns a set of instances that match the lookups kwargs in an instance of QuerySet
For example:
A=Model.objects.get(id=1)
B=Model.objects.filter(id=1)
print(isinstance(A,Model)) # True
print(isinstance(B,QuerySet)) # True
Get sql >>
select * from public.app_model where id=1;
Filter sql >>
select * from public.app_model where id=1;
but at implementation get must return an instance, if the query returns more than 1 row it will raise MultipleObjectsReturned yet filter not, it will return all the rows in Model class instance form
BTW, Both use the cache property

How to display query generated by prefetch_related

I have a QuerySet with a prefetch_related() (with Prefetch object)
I want to see the raw query and print(qs.query) and it doesn't show anything about the prefetch_related stuff.
How do I see the query which will be run because of prefetch_related?
The queryset's query object will only show you the query that Django generates for the queryset itself (before any prefetch_related etc. is applied).
You probably need to look at these guidelines for inspecting the query that is actually sent to your database:
from django.db import connection
print(connection.queries)
Alternatively you can use something like django-debug-toolbar to display the queries.

How does one filter a query set in django

Suppose you have a query set in Django how does one filter it, given that
queryset.objects.filter(condition)
doesn't work?
You should be able to do queryset = queryset.filter(condition) See the QuerySet API

django query is select_related required for subsequent queries?

Given the following code:
progresses = Progress.objects.filter(customer=request.user).select_related()
if id is not None
progress = progresses.get(pk=id)
else:
progress = progresses[0]
Do I need to add select_related() to the second query such as progress = progresses.filter(pk=id).select_related()?
No, your progress queryset object already has the foreign key relationships included in the underlying sql. It's creating a select query with joins. Filtering it further won't remove the joins.
There's an example in the docs of further processing a query that includes select_related (though not using filter).
The order of filter() and select_related() chaining isn’t important.
These querysets are equivalent:
Entry.objects.filter(pub_date__gt=timezone.now()).select_related('blog')
Entry.objects.select_related('blog').filter(pub_date__gt=timezone.now())
From official Django docs: https://docs.djangoproject.com/en/1.9/ref/models/querysets/

django's commit_on_success has no effect on number of sql queries

I'm trying an experiment with bulk saving objects. Using Django Debug Toolbar, I can see how many sql queries are run. However, it seems that the decorator has no affect on the number of SQL queries - it stays the same number with or without the decorator. Should it be decreasing?
#transaction.commit_on_success()
def fastsave(queryset):
for t in queryset:
t.save()
def test(request):
fastsave(TimeEvent.objects.all())
return render_to_response('test.html', {})
No. The transaction decorators only affect when the queries are finalized, not how many are run.
You should use update vs save. See docs here https://docs.djangoproject.com/en/dev/topics/db/queries/#updating-multiple-objects-at-once