Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting by date with a DB in Django

Tags:

python

django

I have the following model.py.

from django.db import models

class Address(models.Model):
    addr = models.CharField(max_length=150)

    def __unicode__(self):
        return u'%s' % (self.addr)

class Anniversary(models.Model):
    date = models.DateField()

    def __unicode__(self):
        return u'%s' % (self.date)

class Person(models.Model):
    name = models.CharField(max_length=50)
    birthday = models.DateField()
    anniversary = models.ForeignKey(Anniversary)
    address = models.ForeignKey(Address)

    def __unicode__(self):
        return u'%s %s %s %s' % (self.name, self.birthday, self.anniversary, self.address)

I want to print the contents of all entries into my template. But sorted by date of birth against the current date. i.e most recent first and then name. What is the best way to do this. Should I sort it first and then append it to a list or dict ?

Any pointers would be great.

Thanks,

like image 340
felix001 Avatar asked Dec 15 '22 13:12

felix001


1 Answers

You can add default ordering in a model's meta class, e.g.

class Person(models.Model):
    # fields
    class Meta:
        ordering = ('anniversary__date',)

then in your template it's as easy as:

<ul>
    {% for person in persons %}
        <li>{{ person.anniversary.date|date:"M d, Y" }} - {{ person.name }}</li>
    {% endfor %}
</ul>

If you need custom ordering within a view (to filter out persons based on the request object):

def myview(request):
    context = dict(
        persons = Person.objects.exclude(person.id=request.user.id)\
                                .order_by('anniversary__date')
    )
    return render_to_response('app/template.html', context)

N.b. Adding a minus before your order_by parameter order_by('-attr') reverses ordering.

As @DanielEriksson mentioned, if your case isn't hypothetic, it seems you should simplify things.

like image 60
Hedde van der Heide Avatar answered Dec 21 '22 11:12

Hedde van der Heide