1
我在HelloWebApp书中有一个名为“Thing”的模型。现在我添加了一个“重量”模型。该模型的字段为“日期”和“weight_value”。在“thing_detail.html”中显示数据时,我想显示按“日期”字段排序的数据。按日期排序所有信息DJANGO
这里是我的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 %}
请别人帮忙!
谢谢!
感谢编辑@kartikmaji –