【发布时间】:2018-11-07 07:15:22
【问题描述】:
这个问题类似于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来呈现响应?你最好在视图中准备这个有序的查询集。
标签: django django-models