A group of data from a database is called a query set.

A list of items is the foundation of a query set.

By enabling you to select and arrange the data early on, QuerySets makes it simpler to obtain the information you truly require.

Working with Django QuerySets

We will be using the Member table to query for data in this tutorial.

idfirstnamelastname phonejoined_date
1Emil Refsnes 55512342022-01-05
2Tobias Refsnes 55577772022-04-01
3 Linus Refsnes  55543212021-12-24
4Lene Refsnes 55512342021-05-01 
5StalikkenRefsnes 55598762022-09-29 

Data Queries

There is a testing view in views.py where we will test all kinds of queries.

The .all() function is used in the example below to retrieve every record and field in the Member model:

View

View .py :

<pre class="language-python"><code>from django.http import HttpResponse
from django.template import loader
from .models import Member

def testing(request):
  mydata = Member.objects.all()
  template = loader.get_template('template.html')
  context = {
    'mymembers': mydata,
  }
  return HttpResponse(template.render(context, request))</code></pre>

The object is sent to the template via the context object as mymembers and is stored in a variable named mydata. It appears as follows:

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

As you can see, there are five records in our Member model, which are represented as five objects in the QuerySet.

The mymembers object in the template can be used to create content:

Template

templates/template.html :

<table border='1'>
  <tr>
    <th>ID</th>
    <th>Firstname</th>
    <th>Lastname</th>
  </tr>
  {% for x in mymembers %}
    <tr>
      <td>{{ x.id }}</td>
        <td>{{ x.firstname }}</td>
      <td>{{ x.lastname }}</td>
    </tr>
  {% endfor %}
</table>

QuerySet Data Access

Data from a model can be obtained into a QuerySet using a variety of techniques.

The methods for values()

Each object can be returned as a Python dictionary with names and values represented as key/value pairs using the values() method:

Example

view . py:

from django.http import HttpResponse
from django.template import loader
from .models import Member

def testing(request):
  mydata = Member.objects.all().values()
  template = loader.get_template('template.html')
  context = {
    'mymembers': mydata,
  }
  return HttpResponse(template.render(context, request))

Retrieving Specific Columns

You can only return the columns you specify using the values_list() method.

view . py:

from django.http import HttpResponse
from django.template import loader
from .models import Member

def testing(request):
  mydata = Member.objects.values_list('firstname')
  template = loader.get_template('template.html')
  context = {
    'mymembers': mydata,
  }
  return HttpResponse(template.render(context, request))

Retrieve Particular Rows

The filter() method allows you to limit the search to only return particular rows or records.

Example

Only return the records with “Emil” as the first name.

view . py:

from django.http import HttpResponse
from django.template import loader
from .models import Member

def testing(request):
  mydata = Member.objects.filter(firstname='Emil').values()
  template = loader.get_template('template.html')
  context = {
    'mymembers': mydata,
  }
  return HttpResponse(template.render(context, request))

QuerySet Filtering

You can limit your search to just retrieve rows that include the search word by using the filter() method.

Filtering on field names like this is possible, as we discovered in the previous chapter:

Example

Only the records with “Emil” as the first name should be returned:

mydata = Member.objects.filter(firstname='Emil').value()

The statement above would be expressed as follows in SQL

SELECT * FROM members WHERE firstname = 'Emil';

AND

You can filter on several fields by separating them with a comma because the filter() method accepts the parameters as **kwargs (keyword arguments).

Example

Return entries with the last name “Refsnes” and the ID 2:

mydata = Member.objects.filter(lastname='Refsnes', id=2).values()

The statement above would be expressed as follows in SQL

SELECT * FROM members WHERE lastname = 'Refsnes' AND id = 2;

OR

It is more difficult to return results where the first name is Emil or Tobias (i.e., records that match either query, but not necessarily both) than it is in the AND example above.

Multiple filter() methods are available, separated by the pipe | character. The outcomes will be combined into a single model.

Example

Return entries with the first names “Emil” or “Tobias”:

mydata = Member.objects.filter(firstname='Emil').values() | Member.objects.filter(firstname='Tobias').values()

Using Q expressions and importing them is another popular technique:

Example

Return entries with the first names “Emil” or “Tobias”:

from django.http import HttpResponse
from django.template import loader
from .models import Member
from django.db.models import Q

def testing(request):
  mydata = Member.objects.filter(Q(firstname='Emil') | Q(firstname='Tobias')).values()
  template = loader.get_template('template.html')
  context = {
    'mymembers': mydata,
  }
  return HttpResponse(template.render(context, request))

The statement above would be expressed as follows in SQL

SELECT * FROM members WHERE firstname = 'Emil' OR firstname = 'Tobias';

Database Field Lookups

Django specifies WHERE clauses and SQL statements in a unique way.

Use “Field lookups” in Django to create specific where clauses.

Specific SQL keywords are represented by field lookups.

Example

Make use of the keyword __startswith

.filter(firstname__startswith='L');

The SQL statement is identical to this:

WHERE firstname LIKE 'L%'

Records whose first name begins with “L” will be returned by the aforementioned statement.

Syntax Guide: Field Lookups

The fieldname must be followed by two (!) underscore characters and the keyword for all field lookups.

The statement would look like this in our Member model:

Example

Provide the entries where the initial letter “L” appears in the first name:

mydata = Member.objects.filter(firstname__startswith='L').values()

Field Lookup Syntax Reference

All of the field lookup keywords are listed here:

KeywordDescription
containsContains the phrase
icontainsSame as contains, but case-insensitive
dateMatches a date
dayMatches a date (day of month, 1-31) (for dates)
endswithEnds with
iendswithSame as endswidth, but case-insensitive
exactAn exact match
iexactSame as exact, but case-insensitive
inMatches one of the values
isnullMatches NULL values
gtGreater than
gteGreater than, or equal to
hourMatches an hour (for datetimes)
ltLess than
lteLess than, or equal to
minuteMatches a minute (for datetimes)
monthMatches a month (for dates)
quarterMatches a quarter of the year (1-4) (for dates)
rangeMatch between
regexMatches a regular expression
iregexSame as regex, but case-insensitive
secondMatches a second (for datetimes)
startswithStarts with
istartswithSame as startswith, but case-insensitive
timeMatches a time (for datetimes)
weekMatches a week number (1-53) (for dates)
week_dayMatches a day of week (1-7) 1 is sunday
iso_week_dayMatches a ISO 8601 day of week (1-7) 1 is monday
yearMatches a year (for dates)
iso_yearMatches an ISO 8601 year (for dates)

Ordering Data with Django QuerySets

The order_by() method in Django is used to sort QuerySets:

Example

Sort the results by first name in alphabetical order:

mydata = Member.objects.all().order_by('firstname').values()

The statement above would be expressed as follows in SQL:

SELECT * FROM members ORDER BY firstname;

Sorting in Descending Order

To change the sorting orientation to descending (highest value first), add the minus sign (NOT), – before the field name. By default, the results are sorted ascending (lowest value first).

Example

Sort the outcome by first name, descending:

mydata = Member.objects.all().order_by('-firstname').values()

The statement above would be expressed as follows in SQL:

SELECT * FROM members ORDER BY firstname DESC;

Specifying Multiple Sort Orders

Use a comma to separate the fieldnames in the order_by() method if you want to order by multiple fields:

Example

Sort the outcome by last name, descending:

mydata = Member.objects.all().order_by('lastname', '-id').values()

The statement above would be expressed as follows in SQL:

SELECT * FROM members ORDER BY lastname ASC, id DESC;

Categorized in: