Python 模型库、实例、迭代和排序依据
这里有几个不同的问题,但它们是混为一谈的 我知道类和实例之间存在差异,但我似乎不知道如何访问后者而不是前者。在民意测验教程1中,他们做q=Question(Question_text=“What's up?”),然后用它做各种事情。但这很容易。此时,只有一个问题对象。当然,我不应该为表中的每一行都创建变量,是吗?一定有更好的办法,但我找不到。例如:Python 模型库、实例、迭代和排序依据,python,django,Python,Django,这里有几个不同的问题,但它们是混为一谈的 我知道类和实例之间存在差异,但我似乎不知道如何访问后者而不是前者。在民意测验教程1中,他们做q=Question(Question_text=“What's up?”),然后用它做各种事情。但这很容易。此时,只有一个问题对象。当然,我不应该为表中的每一行都创建变量,是吗?一定有更好的办法,但我找不到。例如: for a in Articles: print a.sections_set.order_by('id') Traceback (most
for a in Articles:
print a.sections_set.order_by('id')
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: 'ModelBase' object is not iterable
在我看来
我把
class meta:
ordering = ['id']
在我的模型上。什么都不管用
(*)我也把
Articles.objects.order_by('id')
在同样的观点下,这几乎奏效了。除了第六条位于第一条和第二条之间之外,它确实对条款进行了整理。我一次一个地看了一遍,发现
Articles.objects.get(name='Article I')
<Articles: Article I>
A1 = Articles.objects.get(name='Article I')
A1.id
3
Articles.objects.get(name='Article II')
<Articles: Article II>
A2=Articles.objects.get(name='Article II')
A2.id
13
上次我检查时,13比17早。Python/Django对罗马数字有问题吗?如果是这样的话,那么为什么其余的都是正确的顺序呢
这就是杀手:我的模板在基于相同视图代码的迭代中没有任何问题:
{% for a in A %}
<h1><li><a href="{% url 'TOC' %}">{{ a.name }} {{ a.popular_name }}</a></li></h1>
{% for section in a.sections_set.all %}
<h2><li><a href="{% url 'TOC' %}">{{ section.name }} {{ section.popular_name }}</a></li></h2>
{% endfor %}
{% endfor %}
最后,在教程3中,当他们引入render时,他们在没有解释的情况下使用order_by更改代码,从
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
到
如果它们a)保持一致,b)解释这样的更改,这将有助于我理解如何使用它。您问题的第二部分似乎完全回答了第一部分:要遍历所有文章,您可以使用
对象管理器,即Article.objects.all()
返回它们,Article.objects.order\u by('whatever')
修改排序,或Article.objects.filter(fieldname=whater)
查询特定字段值
对于第二部分,Django当然对罗马数字一无所知:其中一些数字是有序的这一事实是巧合。而且您也不应该依赖主键--id
——来进行订购:如果您删除并重新创建一个项目,您将获得更高的id,因为数据库通常不会重用id。您应该在模型上添加一个特定的order
字段,并按该字段排序
最后,模板语言根本不允许使用参数调用函数,这就是为什么会出现这种错误
Articles.objects.get(name='Article I')
<Articles: Article I>
A1 = Articles.objects.get(name='Article I')
A1.id
3
Articles.objects.get(name='Article II')
<Articles: Article II>
A2=Articles.objects.get(name='Article II')
A2.id
13
A6=Articles.objects.get(name='Article VI')
A6.id
17
{% for a in A %}
<h1><li><a href="{% url 'TOC' %}">{{ a.name }} {{ a.popular_name }}</a></li></h1>
{% for section in a.sections_set.all %}
<h2><li><a href="{% url 'TOC' %}">{{ section.name }} {{ section.popular_name }}</a></li></h2>
{% endfor %}
{% endfor %}
{% for a in A %}
<h1><li><a href="{% url 'TOC' %}">{{ a.name }} {{ a.popular_name }}</a></li></h1>
{% for section in a.sections_set.order_by('id') %}
<h2><li><a href="{% url 'TOC' %}">{{ section.name }} {{ section.popular_name }}</a></li></h2>
{% endfor %}
{% endfor %}
Could not parse the remainder: '('id')' from 'a.sections_set.order_by('id')'
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
def index(request):
latest_question_list = Question.objects.all().order_by('-pub_date')[:5]