What is a Django QuerySet?

DjangoDjango Queryset

Django Problem Overview


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).

Django Solutions


Solution 1 - Django

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).

Solution 2 - Django

Solution 3 - Django

A QuerySet represents a collection of objects from your database. It can have zero, one or many filters. Filters narrow down the query results based on the given parameters. In SQL terms, a QuerySet equates to a SELECT statement, and a filter is a limiting clause such as WHERE or LIMIT.

https://docs.djangoproject.com/en/1.8/topics/db/queries/

Solution 4 - Django

A QuerySet is a list of objects of a given model, QuerySet allow you to read data from database

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiongathView Question on Stackoverflow
Solution 1 - DjangoBernhard VallantView Answer on Stackoverflow
Solution 2 - DjangoIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 3 - DjangoHarshit GargView Answer on Stackoverflow
Solution 4 - DjangoPythonsguruView Answer on Stackoverflow