按日期排序所有信息DJANGO

时间:2016-03-04 18:35:40

标签: python django web-applications backend

我有一个名为" Thing"就像在HelloWebApp书中一样。现在我已经添加了一个"体重"模型。该模型有字段" date"和" weight_value"。在" thing_detail.html"中显示数据时我想显示按字段排序的数据" date"。

以下是我的models.py

from django.db import models
from django.contrib.auth.models import User
from django.db import models
from django.utils import timezone

class Thing(models.Model):
    name = models.CharField(max_length=255)
    description = models.TextField()
    slug = models.SlugField(unique=True)
    user = models.OneToOneField(User, blank=True, null=True)

class Weight(models.Model):
    date = models.DateTimeField(default=timezone.now)
    weight_value = models.CharField(max_length=255)
    thingRA = models.ForeignKey(Thing,related_name="weights")

    class Meta:
        order_with_respect_to = 'thingRA'

和thing_details.html

{% extends 'layouts/base.html' %}
{% block title %}
{{ thing.name }} - {{ block.super }}
{% endblock %}
{% block content %}
<div id="content">
<!-- Below is to check if the data belongs to the original user -->
{% if user == thing.user %}
<h1>{{ thing.name }}</h1>
<p>{{ thing.description }}</p><br>
{% if weights %}
    {% for weightshow in weights %}
        <p>>Weight as on {{weightshow.date}} : {{weightshow.weight_value}}</p>
    {% empty %}
        <p>Sorry! You haven't logged any weight records yet</p>
   {% endfor %}
{% endif %}
<br><br>
<a href="{% url 'edit_thing' slug=thing.slug %}"><u>Edit Me!</u></a>
<br>
<a href="{% url 'edit_weight' slug=thing.slug %}"><u>Log Weight Record!</u></a>
</div>
{% else %}
<h1>Error!</h1>
<p>You do not have the permission to view this account. If this is your account please logout and login to <strong>{{thing.name}}</strong></p><br>
{% endif %}
{% endblock %}

请有人帮忙!

谢谢!

1 个答案:

答案 0 :(得分:1)

在您的体重模型

中添加此项
class Meta:
    ordering = ['date']

或者在进行查询时添加order_by()。喜欢,

Weight.objects.all().order_by('date')