Listview上的Django过滤查询

时间:2018-05-29 08:26:54

标签: python django

我有一个案例需要显示用户将在1个月后过期,并且用户已经在1个月以后加入了该视图。

以下是我template.html的样子:

+-------------------------------------+  +-------------------------------------+
| Member will Expired in 30 days      |  | New Member Almost 30 Days           |
+-------------------------------------+  +-------------------------------------+
| Name            | Expired in        |  | Name            | 1 Month in        | 
+-------------------------------------+  +-------------------------------------+
| John            | 12 Hours          |  | Alex            | 12 Hours          |
| Doe             | 10 Days           |  | Monroe          | 12 Days           |
| Sue             | 30 Days           |  | Zax             | 28 Days           |
+-------------------------------------+  +-------------------------------------+

这是我的template.html代码

...
{% for a in dashboards %}
<tr>
  <td>{{ a.name }}</td>
  <td>{{ a.membership_till|naturaltime }}</td>
</tr>
{% endfor %}
...    

...
{% for a in dashboards %}
<tr>
  <td>{{ a.name }}</td>
  <td>{{ a.membership_till|naturaltime }}</td>
</tr>
{% endfor %}
...

这是我的model.py

class User(models.Model):
    ...
    name = models.CharField(max_length=255)
    joined_date = models.DateTimeField(max_length=255)
    membership_till = models.DateTimeField(max_length=255)
    ...

这是我的views.py

class DashboardListView(ListView):
    template_name = 'index.html'
    context_object_name = 'dashboards'
    model = models.User

目前,我只能在不过滤的情况下显示两张桌子上的所有数据。

我需要显示2 <table> 2个不同的功能,但我不知道如何过滤template.html

1 个答案:

答案 0 :(得分:4)

就像名称ListView建议的那样,视图实际上只适用于一个查询集。如果您想使用更多元素,可以修补get_context_data 功能:

from datetime import datetime, timedelta

class DashboardListView(ListView):
    template_name = 'index.html'
    context_object_name = 'dashboards'
    model = models.User

    def get_context_data(self, *args, **kwargs):
        context = super(DashboardListView, self).get_context_data(*args, **kwargs)

        now = datetime.now()
        d30 = timedelta(30)
        context['expire'] = User.objects.filter(membership_till__lt=now+d30)
        context['new'] = User.objects.filter(joined_date__gt=now-d30)

        return context

因此我们在上下文中添加了两个额外的查询集,然后我们可以在template.html中使用它们:

...
{% for a in expire %}
<tr>
  <td>{{ a.name }}</td>
  <td>{{ a.membership_till|naturaltime }}</td>
</tr>
{% endfor %}
...    

...
{% for a in new %}
<tr>
  <td>{{ a.name }}</td>
  <td>{{ a.membership_till|naturaltime }}</td>
</tr>
{% endfor %}
...