Sort by date using DB in 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 the entries in my template. But sorted by date of birth versus current date. ie the very last first and then the name. What is the best way to do this. Should I sort it first and then add it to a list or dict?

Any pointers would be great.

Thanks,

+4
source share
4 answers

You can add a default order in the meta-class of the model, for example.

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

then in your template it will be simple:

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

If you need an individual order in the view (to filter people 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) 

Nb Adding a minus before the order_by parameter order_by order_by('-attr') cancels the order.

As @DanielEriksson said, if your case is not hypothetical, it seems you need to simplify things.

+11
source

I think you are looking for this:

  persons = Person.objects.all().order_by(birthday ,anniversary) 

In the view, you can get the current date using:

  import datetime now = datetime.datetime.now() 

and then:

  persons = Person.objects.all().order_by(now, anniversary) 

Hope this helps!

0
source

I personally like to avoid sorting in Models, as this is more relevant to the view / view. I use sorting in render_to_response to sort by a single value or order_by for multi-valued sorting. Using sorting in the return statement allows me to split the difference between the view / template, since Django views are not completely controllers. In any case, this is only my preference. You can also use dictsort in the template to sort by one value.

You indicated that you want to sort using several values, first by the most recent date of birth, and then by name. To do this, I would use order_by in the view, and then comment out my return statement:

 from django.shortcuts import render_to_response def view_persons(request): persons = Person.objects.all().order_by('-birthday', 'name') return render_to_response( 'view_persons.html', { 'persons': persons, # ordered by most recent birthday, then name }, context_instance=RequestContext(request) ) 

In the template, you have a little more than:

 {% if persons %} <table> <thead> <tr> <th>Birthday</th> <th>Name</th> </tr> </thead> <tbody> {% for person in persons %} <tr> <td>{{ person.birthday }}</td> <td>{{ person.name }}</td> </tr> {% endfor %} </tbody> </table> {% else %} <p>There are no people!</p> {% endif %} 
0
source

I guess the difficulty is that you need to compare the sorted date with the current date, and not just sorted by date.

If you use Postgres and are happy to stick with raw SQL, you can use their datetime functions such as age

http://www.postgresql.org/docs/8.1/static/functions-datetime.html

Otherwise, you will need to choose where the date of birth / anniversary is greater than now. It might be easier if you reorganized your anniversary model to keep the day, month, and year separate fields so you can ignore the year when filtering.

I recently posted some code in a question that might give you some hints - I need to return the events closest to date. Cm:

Is it wrong to return a tuple from a Django Manager method instead of a set of queries?

0
source

All Articles