Django QuerySet

Django QuerySet

Django QuerySet

A QuerySet is a collection of data from a database.

A QuerySet is built up as a list of objects.

QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.

In this tutorial we will be querying data from the Members table.


id firstname lastname
1 Emil Refsnes
2 Tobias Refsnes
3 Linus Refsnes
4 Lene Refsnes
5 Stalikken Refsnes

Querying Data

In, we have a view for testing called testing where we will test different queries.

In the example below we use the .all() method to get all the records and fields of the Members model:



The object is placed in a variable called mydata, and is sent to the template via the context object as mymembers, and looks like this:

<QuerySet [
  <Members: Members object (1)>,
  <Members: Members object (2)>,
  <Members: Members object (3)>,
  <Members: Members object (4)>,
  <Members: Members object (5)>

As you can see, our Members model contains 5 records, and are listed inside the QuerySet as 5 objects.

In the template you can use the mymembers object to generate content:



Run Example »