【发布时间】:2016-07-28 16:40:31
【问题描述】:
我有类似的模型:
class BaseInfo(models.Model):
is_active = models.BooleanField(default=True)
# other fields..
class Meta:
abstract = True
class Customer(BaseInfo):
name = models.CharField(max_length=50)
## other fields..
在模板中我想显示这个模型的表格,但我想突出显示不活动的表格。所以我在模板中有这个片段:
{% for c in customers %}
<tr {%if not c.is_active %}class="not-active" {%endif%}>
<td>..</td>
</tr>
{% endfor %}
现在,我想在此旁边显示活跃的 NUMBER 个。 我可以这样做:
all = Customer.objects.filter(name="foo")
excludeInactive = all.filter(is_active=False)
然后在上下文中传递两者。 但我更喜欢模板中这样的东西:
{{customers.exclude_deleted.count}}
或者也许:
{{customers.exclude_deleted|length}}?
我有更多模型继承了这个抽象类。所以我认为基类的经理可以工作吗?我只是不明白如何写一个..
另外,性能怎么样?如果我对.filter() 进行两次调用,会导致两个数据库查询,即使第二个查询是已评估查询集的子集?
【问题讨论】:
-
看看自定义模板标签
-
您可能需要为此目的查看自定义管理器。
标签: django django-models filter subset django-queryset