我有一个称为“统计”的模型。从视图中,我创建了一个ListView使其显示在模板上。现在我的问题是我只想看到today's == date_expiry
。如何使用ListView
来做到这一点?
models.py
class Statistics(models.Model):
site = models.CharField(max_length=264)
name = models.CharField(max_length=264, blank=True)
mac_add = models.CharField(max_length=264)
minutes_used = models.CharField(max_length=265)
date = models.DateTimeField(auto_now=True, blank=True)
date_expiry = models.DateTimeField()
def __str__(self):
return self.name
views.py
class DisplayStats(ListView):
model = Statistics
ordering = ['date']
html
<table class="table">
<tr>
<th>Site</th>
<th>Name</th>
<th>Mac ID</th>
<th>Hours</th>
<th>Date</th>
<th>Date Expired</th>
</tr>
{% for clients in object_list %}
<tr>
<td>{{ clients.site }}</td>
<td>{{ clients.name }}</td>
<td>{{ clients.mac_add }}</td>
<td>{{ clients.minutes_used|cut:".0" }}</td>
<td>{{ clients.date }}</td>
<td>{{ clients.date_expiry }}</td>
</tr>
{% endfor %}
</table>
答案 0 :(得分:1)
您可以过滤它。
import datetime
class DisplayStats(ListView):
model = Statistics
ordering = ['date']
def get_queryset(self):
# python3
queryset = super().get_queryset()
# if python2
# queryset = super(DisplayStats, self).get_queryset()
queryset.filter(date_expiry=datetime.date.today())
return queryset
答案 1 :(得分:1)
您可以仅过滤查询集。您可以通过两种方式做到这一点:
覆盖queryset
import datetime
class DisplayStats(ListView):
model = Statistics
queryset = Statistics.objects.filter(date_expiry=datetime.date.today())
ordering = ['date']
使用get_queryset()
import datetime
class DisplayStats(ListView):
model = Statistics
ordering = ['date']
def get_queryset(self):
return Statistics.objects.filter(date_expiry=datetime.date.today())