这个问题就像 django sorting但我无法让任何解决方案发挥作用。
我有以下型号:
from django.db import models
from django.contrib.auth.models import User
class Product(models.Model):
title = models.CharField(max_length=200)
pub_date = models.DateTimeField()
body = models.TextField()
url = models.TextField()
image = models.ImageField(upload_to='images/')
icon = models.ImageField(upload_to='images/')
votes_total = models.IntegerField(default=1)
hunter = models.ForeignKey(User, on_delete=models.CASCADE)
def summary(self):
return self.body[:50]
def pub_date_pretty(self):
return self.pub_date.strftime('%b %e %Y')
def __str__(self):
return self.title
我想按 votes_total 排序,这样当我遍历数据库时,结果按 votes_total 排序。
{% extends 'base.html' %}
{% block content %}
{% for product in products.all %}
<div class="row pt-3">
<div class="col-2" onclick="window.location='{% url 'detail' product.id %}';" style="cursor:pointer">
<img src="{{ product.icon.url }}" class="img-fluid" alt="">
</div>
<div class="col-6" onclick="window.location='{% url 'detail' product.id %}';" style="cursor:pointer">
<h1>{{ product.title }}</h1>
<p>{{ product.summary }}</p>
</div>
<div class="col-4" onclick="window.location='{% url 'detail' product.id %}';" style="cursor:pointer">
<a href="javascript:{document.getElementById('upvote{{ product.id }}').submit()}"><button class="btn btn-primary btn-lg btn-block"><span class="oi oi-caret-top"></span> Upvote {{ product.votes_total }}</button></a>
</div>
</div>
<form id="upvote{{ product.id }}" method="POST" action="{% url 'upvote' product.id %}">
{% csrf_token %}
<input type="hidden">
</form>
{% endfor %}
{% endblock %}
如何对结果进行排序?
最佳答案
基本上有两种方法可以做到这一点:
- 在 View 中定义排序;或
- 在模型中定义一个默认排序(可以被另一个排序覆盖的排序)。
如果模型具有合理(固有)排序,则通常使用最后一个选项(例如,以某种方式对查询集进行排序是非常合乎逻辑的,并且只是偶尔以另一种方式排序)。
在 View 中排序
我们可以使用 .order_by(..)
对查询集进行排序。查询集的功能。该函数采用任意数量的参数:指定列名的字符串。如果列名以减号 (-
) 为前缀,则表示我们按降序排序。
例如我们可以定义一个 View :
def some_view(request):
my_products = Product.objects.all()<b>.order_by('-votes_total')</b>
return render(request, 'my_template.html', {<b>'my_products': my_products</b>})
然后我们可以使用这个 'my_products'
变量,并对其进行迭代:
{% extends 'base.html' %}
{% block content %}
{% for product in <b>my_products</b> %}
<div class="row pt-3">
<div class="col-2" onclick="window.location='{% url 'detail' product.id %}';" style="cursor:pointer">
<img src="{{ product.icon.url }}" class="img-fluid" alt="">
</div>
<div class="col-6" onclick="window.location='{% url 'detail' product.id %}';" style="cursor:pointer">
<h1>{{ product.title }}</h1>
<p>{{ product.summary }}</p>
</div>
<div class="col-4" onclick="window.location='{% url 'detail' product.id %}';" style="cursor:pointer">
<a href="javascript:{document.getElementById('upvote{{ product.id }}').submit()}"><button class="btn btn-primary btn-lg btn-block"><span class="oi oi-caret-top"></span> Upvote {{ product.votes_total }}</button></a>
</div>
</div>
<form id="upvote{{ product.id }}" method="POST" action="{% url 'upvote' product.id %}">
{% csrf_token %}
<input type="hidden">
</form>
{% endfor %}
{% endblock %}
在模型上定义排序
如果某个排序从模型的角度来看是非常合乎逻辑的,我们也可以将排序封装在模型本身中。我们使用属性的 Meta
类的 ordering
属性来指定它。例如,如果我们希望默认按 降序 的投票数对 Product.objects.all()
进行排序,我们可以这样写:
class Product(models.Model):
title = models.CharField(max_length=200)
pub_date = models.DateTimeField()
body = models.TextField()
url = models.TextField()
image = models.ImageField(upload_to='images/')
icon = models.ImageField(upload_to='images/')
votes_total = models.IntegerField(default=1)
hunter = models.ForeignKey(User, on_delete=models.CASCADE)
class Meta:
<b>ordering = ['-votes_total']</b>
所以现在我们仍然可以在模板中访问Product.objects.all
,元素会自动排序。
但是请注意,我们只能为每个模型定义一个这样的排序,从而做出特定的决定,不能基于特定的 View 来指定。如果您想“覆盖”排序,您需要在查询集上使用 order_by
。
关于django - 在 Django 2.0 中按字段值排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50570689/