开发者

Django annotate on a "custom field" with django-sorting

I have to show entries by date in a django app and i'm a bit blocked : Here's 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 got a view that take all the events in the database : Event.objects.all()

and then in a template i show the list of events with their theme and other stuffs like the date start. I would like to show in the list the first "future" date, that's easy 开发者_运维知识库with a custom method on 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]

That method the first future date or the oldest date that isn't finished.

Here's 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 %} to do it but i don't know how to manage that field in it... How would you do that???

Thanks by advance for any answer.


Your question is unclear, why would you sort the queryset by the end field when get_first_future_date returns just one instance of Event ?

Well, I've never used django-sorting, but I assume I would 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 it what you were asking for ?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜