Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

Django 查询集


Django 查询集

查询集是数据库中数据的集合。

查询集构建为对象列表。

查询集通过允许您在早期阶段过滤和排序数据,使您更容易获取您实际需要的数据。

在本教程中,我们将从 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 


查询数据

views.py 中,我们有一个用于测试的视图,名为 testing,我们将在其中测试不同的查询。

在下面的示例中,我们使用 .all() 方法获取 Member 模型的所有记录和字段

视图

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

该对象放置在一个名为 mydata 的变量中,并通过 context 对象作为 mymembers 发送到模板,它看起来像这样

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

正如您所看到的,我们的 Member 模型包含 5 条记录,并在查询集中列出为 5 个对象。

在模板中,您可以使用 mymembers 对象生成内容

模板

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>
运行示例 »


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

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-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.