Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a Django QuerySet?

When I do this,

>>> b = Blog.objects.all() >>> b 

I get this:

>>>[<Blog: Blog Title>,<Blog: Blog Tile>] 

When I query what type b is,

>>> type(b) 

I get this:

>>> <class 'django.db.models.query.QuerySet'> 

What does this mean? Is it a data type like dict, list, etc?

An example of how I can build data structure like a QuerySet will be appreciated.

I would want to know how Django builds that QuerySet (the gory details).

like image 906
gath Avatar asked Jan 13 '11 14:01

gath


People also ask

Is Django QuerySet lazy?

This is because a Django QuerySet is a lazy object. It contains all of the information it needs to populate itself from the database, but will not actually do so until the information is needed.

What is a Django ORM?

One of the most powerful features of Django is its Object-Relational Mapper (ORM), which enables you to interact with your database, like you would with SQL. In fact, Django's ORM is just a pythonical way to create SQL to query and manipulate your database and get results in a pythonic fashion.

What is F object Django?

An F() object represents the value of a model field, transformed value of a model field, or annotated column. It makes it possible to refer to model field values and perform database operations using them without actually having to pull them out of the database into Python memory.


1 Answers

A django queryset is like its name says, basically a collection of (sql) queries, in your example above print(b.query) will show you the sql query generated from your django filter calls.

Since querysets are lazy, the database query isn't done immediately, but only when needed - when the queryset is evaluated. This happens for example if you call its __str__ method when you print it, if you would call list() on it, or, what happens mostly, you iterate over it (for post in b..). This lazyness should save you from doing unnecessary queries and also allows you to chain querysets and filters for example (you can filter a queryset as often as you want to).

like image 76
Bernhard Vallant Avatar answered Sep 21 '22 20:09

Bernhard Vallant