Use order_by in Django

2

I try to sort a post list in Django. I read that you have to use .order_by('-fecha') . I have tried the following in the template:

{% for post in persona.post_set.all.order_by('-fecha') %}
    {{ post.texto }}<br>
{% endfor %}

But it returns this error:

  

Could not parse the remainder: '(-date)' from 'person.post_set.all.order_by (-date)'

How could I sort the post so that the last post that was posted is the first one?

    
asked by ImHarvol 01.08.2017 в 08:55
source

2 answers

4

You have several options.

If it makes sense that your posts are always sorted by date, you can indicate it in the model itself.

class Post(Model):
    # ...
    fecha = DateTimeField(...)

    class Meta:
        # sort by "fecha" in descending order unless
        # overridden in the query with order_by()
        ordering = ['-fecha']

Another option is to create a property in the model that allows you to get the ordered posts:

class Persona(models.Model):
    # ...
    @property
    def sorted_post_set(self):
        return self.post_set.order_by('-fecha')

Another option is to pass to the template a list of already ordered posts instead of a queryset.

def persona_view(request, persona_id):
    persona = Persona.objects.get(pk=persona_id)
    ordered_posts = persona.post_set.order_by('-fecha')
    context = {'persona': persona, 'ordered_post': ordered_post}
    return render(request, 'myapp/persona_template.html', context)
    
answered by 01.08.2017 / 09:38
source
2

The easiest thing is to manage that part in the view.py

personas = Persona.objects.all().order_by('-fecha')

and you send the result persona to your template .html to be able to iterate

{% for p in personas %}
    <p>{{ p.texto }}</p>
{% endfor %} 
    
answered by 02.08.2017 в 07:54