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,
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With