Django annotates "custom field" with django sort

I need to show records by date in a django app and I am a bit blocked: Here is an example of my models:

class Event(models.Model):  
    name = models.CharField(max_length=100)  
    theme = models.ForeignKey(Theme)
    ...

class Date(models.Model):  
    event = models.ForeignKey(Event)  
    start = models.DateField()  
    end = models.DateField()

    class Meta:
        ordering = ['start', 'end']
        unique_together = ['event', 'start']

      

I have a view that accepts all events in the database: Event.objects.all ()

and then in the template I will show the list of events with their subject and other stuff like start date. I would like to show the first "future" date in the list, which is easy with a custom method in the event model:

def get_first_future_date(self):
    today = datetime.datetime.now()
    dates = self.date_set.filter(end__gte=today)
    if dates:
        return dates[0]

      

This method is the first date in the future or the oldest date that is not yet complete.
Here the problem : I would like to show that field in my template and be able to sort it with django-sorting.

Django-sorting uses {% anchor arg%} for this, but I don't know how to manipulate this field in it ... How would you do that?

Thanks in advance for any answer.

+2


a source to share


1 answer


Your question is not clear why you are sorting the query into a field end

when get_first_future_date

only one instance of the event is returned?

Well I have never used django collation, but I guess I will do

events = Event.objects.all() # or filter(...)
# pass events to the template context

      



and then in the template

{% load sorting_tags %}
{% autosort events %}
<thead>
   <th>{% anchor start Starting at %}</th>
   <th>{% anchor end Ending at %}</th>
    ...
</thead>
{% for event in events %}
<tr>
    <td>{{event.start}}</td>
    ...
</tr>
{% endfor %}

      

Is this what you are asking for?

0


a source







All Articles