【问题标题】:Query database based on id in djangodjango中根据id查询数据库
【发布时间】:2016-11-07 15:36:46
【问题描述】:

我在 django 中有以下模型。

class Choices(models.Model):
    question = models.CharField(max_length=200)
    option1 = models.CharField(max_length=200)
    option2 = models.CharField(max_length=200)
    option3 = models.CharField(max_length=200)

我想在我的模板中显示 id=1 的 option2 字段的元素。 有什么办法可以做到吗?

谢谢。

【问题讨论】:

标签: python html django sqlite


【解决方案1】:

您应该在视图中获取Choice,然后将其传递给您的模板。示例:

view.py

from django.shortcuts import get_object_or_404, render

def my_view(request, choice_id):
    choice = get_object_or_404(Choice, id=choice_id)
    return render(request, "my_template.html", {"choice": choice}

my_template.html

<html>
  <body>
    {{ choice.option2 }}
  </body>
</html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-03
    • 1970-01-01
    • 1970-01-01
    • 2015-12-21
    • 2011-10-31
    • 1970-01-01
    相关资源
    最近更新 更多