代码之家  ›  专栏  ›  技术社区  ›  Dicky Raambo

ListView上的Django筛选器查询

  •  4
  • Dicky Raambo  · 技术社区  · 6 年前

    我有一个案例需要证明用户将在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           |
    +-------------------------------------+  +-------------------------------------+
    

    这是我的 模板.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> 有两种不同的功能,但我不知道如何过滤 模板.html .

    1 回复  |  直到 6 年前
        1
  •  4
  •   willeM_ Van Onsem    6 年前

    很喜欢这个名字 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 %}
    ...