【问题标题】:Django - Getting values from ModelDjango - 从模型中获取值
【发布时间】:2018-10-15 05:09:19
【问题描述】:

我想从Model OUTSIDE 循环在我的模板.html 中发布type value。我可以在循环中获得价值。
我的模型看起来像:
models.py:

class Post(models.Model):
    TYPE = ( ("test", "test"), )
    ...
    type = models.CharField(max_length=13, choices=TYPE, default="")


views.py:

def post_type(request, type):
    posts = Post.objects.filter(type=type)
    return render(request, 'blog/post_type.html', {'posts': posts})


.html:

{% block some_block %}

    {{ posts.type}} # DOES NOT WORK - (Getting QuerySet[] only, but cannot call to {{posts.type}} or, let's say, {{ post.type[0] }} to just get that type.

    {% for post in posts %}
        {{ post.type }} # This works fine in Loop, cos Im inside set... (I can call even to post.title if defined in Model)
    {% endfor %}

{% endblock %}


:(

----- 编辑:----
{{posts.0.type}} 解决问题

【问题讨论】:

    标签: django django-models django-templates


    【解决方案1】:

    尝试在模板中使用它

    {{ posts.0.type }}
    

    【讨论】:

      【解决方案2】:

      发生这种情况是因为:
      posts = Post.objects.filter(type=type) - 返回 QuerySet,而不是 Post 的实例。
      您可以尝试:
      post1 = Post.objects.filter(type=type)[0] - 获取第一个Posttype 的值。

      【讨论】:

        【解决方案3】:

        {{posts.0.type}} 也可以,谢谢

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-01-05
          • 2020-09-19
          • 1970-01-01
          • 2017-09-14
          • 1970-01-01
          • 2013-09-23
          相关资源
          最近更新 更多