【问题标题】:Django annotate on a "custom field" with django-sortingDjango 使用 django-sorting 在“自定义字段”上进行注释
【发布时间】:2010-05-17 14:33:54
【问题描述】:

我必须在 django 应用程序中按日期显示条目,但我有点受阻: 这是我的模型示例:

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']

我得到了一个包含数据库中所有事件的视图:Event.objects.all()

然后在模板中显示事件列表及其主题和其他内容,例如开始日期。 我想在列表中显示第一个“未来”日期,这很容易使用事件模型上的自定义方法:

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

该方法是第一个未来日期或未完成的最早日期。
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 使用 {% anchor arg %} 来做到这一点,但我不知道如何在其中管理该字段... 你会怎么做???

提前感谢您的任何回答。

【问题讨论】:

  • 我陷入了同样的境地。您找到解决方案了吗?

标签: django sorting annotate


【解决方案1】:

您的问题不清楚,当get_first_future_date 仅返回一个事件实例时,为什么要按end 字段对查询集进行排序?

好吧,我从未使用过 django-sorting,但我想我会这样做

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

然后在模板中

{% 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 %}

这是你要求的吗?

【讨论】:

    猜你喜欢
    • 2019-07-21
    • 2012-09-21
    • 1970-01-01
    • 2019-09-03
    • 2018-03-21
    • 2023-01-27
    • 2021-07-31
    • 2014-05-18
    • 2014-05-15
    相关资源
    最近更新 更多