Shashank Shekhar
Shashank Shekhar

Reputation: 105

Sort All the Information by Date DJANGO

I have a model named "Thing" as in the HelloWebApp book. Now I've added a "weight" model. The model has fields "date" and "weight_value". While displaying the data in "thing_detail.html" I want to display the data ordered by the field "date".

Here are my 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'

and 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 %}

Kindly someone help!

Thanks!

Upvotes: 1

Views: 61

Answers (1)

kartikmaji
kartikmaji

Reputation: 976

Add this in your Weight model

class Meta:
    ordering = ['date']

Or when you are making query add order_by(). Like,

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

Upvotes: 1

Related Questions