[フレーム]

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 at an early stage.

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

Member:

id firstname lastname phone joined_date
1 Emil Refsnes 5551234 2022年01月05日
2 Tobias Refsnes 5557777 2022年04月01日
3 Linus Refsnes 5554321 2021年12月24日
4 Lene Refsnes 5551234 2021年05月01日
5 Stalikken Refsnes 5559876 2022年09月29日


Querying Data

In views.py, 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 Member model:

View

views.py:

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

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 [
<Member: Member object (1)>,
<Member: Member object (2)>,
<Member: Member object (3)>,
<Member: Member object (4)>,
<Member: Member object (5)>
]>

As you can see, our Member 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:

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>
Run Example »


Track your progress - it's free!
×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

FORUM ABOUT ACADEMY
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.

AltStyle によって変換されたページ (->オリジナル) /