【问题标题】:Python django custom query result in htmlhtml中的Python django自定义查询结果
【发布时间】:2016-11-15 09:25:49
【问题描述】:

刚开始学习python django框架,我正在尝试在html页面中显示自定义查询结果。

def index(request):
    with connection.cursor() as cursor:
        cursor.execute("SELECT * FROM polls_post")
context ={
        'all_posts':cursor.fetchall()
    }

在我的html页面中

<ul>
        {%  for post in all_posts %}
            <li>{{ post }}</li>
        {% endfor %}
    </ul>

但是它将值显示为元组,所以我怎样才能得到带有表列名的查询结果,比如我可以这样打印值

<ul>
            {%  for post in all_posts %}
                <li>{{ post.title }}</li>
                <li>{{ post.name }}</li>
            {% endfor %}
        </ul>

【问题讨论】:

  • 如果您刚开始学习 Django,是什么让您认为最好的方法是运行原始 SQL 查询而不是使用文档齐全的模型层?
  • 我需要知道这是可能的,仅此而已:)

标签: python django


【解决方案1】:

你不能 - 使用光标你需要自己在视图内重新打包数据,然后将 objects 列表传递给模板。

类似

posts = []

with connection.cursor() as cursor:
    cursor.execute("SELECT * FROM polls_post")

    for obj in cursor.fetchall():
        posts.append({"title": obj[0], "name": obj[1]})
context = {'all_posts':cursor.fetchall()}

不过,我想您更愿意使用 Django 的 ORM 框架。那就看看Model reference吧。

【讨论】:

【解决方案2】:

为什么在你的视图中使用 sql 查询。尝试使用Django ORM and QuerySets

也许这对你有帮助

Django 视图

def your_view(request):
    all_posts = your_model_class_name.objects.all()
    return render_to_response("your_html.html", {'all_posts': all_posts})

在你的html页面中

<ul>
    {%  for post in all_posts %}
        <li>{{ post.title }}</li>
        <li>{{ post.name }}</li>
    {% endfor %}
</ul>

【讨论】:

  • 我会在polls_post得到未解决的引用错误
  • 柱子是你的班级名称,请替换它。
  • 所以我需要使用 ORM 层但我不需要它
【解决方案3】:

你也可以这样做

def your_view(request):
    all_posts = model_class_name.objects.raw("Select * from tablename");
    return render_to_response("your_html.html", {'all_posts': all_posts})

在模板中

<ul>
    {%  for post in all_posts %}
        <li>{{ post.title }}</li>
        <li>{{ post.name }}</li>
    {% endfor %}
</ul>

原始查询在我们使用复杂查询时很有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-11
    • 2016-03-16
    • 2016-04-07
    • 1970-01-01
    相关资源
    最近更新 更多