Django-从模型中获取值
我想从Django-从模型中获取值,django,django-models,django-templates,Django,Django Models,Django Templates,我想从Model外部循环获取模板.html中的post类型值。我可以在循环中得到值 我的模型看起来像: models.py: class Post(models.Model): TYPE = ( ("test", "test"), ) ... type = models.CharField(max_length=13, choices=TYPE, default="") def post_type(request, type): posts = Post.obj
Model
外部循环获取模板.html
中的post类型值。我可以在循环中得到值
我的模型看起来像:
models.py
:
class Post(models.Model):
TYPE = ( ("test", "test"), )
...
type = models.CharField(max_length=13, choices=TYPE, default="")
def post_type(request, type):
posts = Post.objects.filter(type=type)
return render(request, 'blog/post_type.html', {'posts': posts})
{% 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 %}
视图.py
:
class Post(models.Model):
TYPE = ( ("test", "test"), )
...
type = models.CharField(max_length=13, choices=TYPE, default="")
def post_type(request, type):
posts = Post.objects.filter(type=type)
return render(request, 'blog/post_type.html', {'posts': posts})
{% 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 %}
.html
:
class Post(models.Model):
TYPE = ( ("test", "test"), )
...
type = models.CharField(max_length=13, choices=TYPE, default="")
def post_type(request, type):
posts = Post.objects.filter(type=type)
return render(request, 'blog/post_type.html', {'posts': posts})
{% 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}
解决问题发生这种情况的原因是:
posts=Post.objects.filter(type=type)
-返回QuerySet
,而不是Post
的实例
您可以试试:
post1=Post.objects.filter(type=type)[0]
-若要获取第一次Post的type
值,请尝试在模板中使用该值
{{ posts.0.type }}
{{posts.0.type}}
也可以,谢谢