Django - 过滤模板中的RelatedManager _set?

标签 django templates filter

我们有一个 Django DetailView,在其中显示一个对象 (Site) 及其所有相关对象 (Rooms)。

现在,在模板中,我们可以简单地迭代相关管理器集:

{% for room in site.room_set.all %}
    do stuff
{% endfor %}

但是,这样做的问题是,这将拾取与站点相关的所有房间 - 但是,我们需要通过另一个属性(让我们称之为年份)稍微缩小这个集合的范围) - 此属性存储在 Django session 变量中。

目前,我们仅在 View 代码中使用 Room.objects.filter(site=some_site,year='2009'),这很好。

我的问题更多是出于好奇 - 有没有办法在模板中使用 _set ,并且仍然过滤或缩小集合范围?

您可以编写一个自定义模型管理器来执行此操作,以便 _set 只返回当年的对象吗?或者还有其他办法吗?

干杯, 维克多

最佳答案

My question is more from curiosity - is there any way to use _set in the template, and still filter down or narrow the set?

默认情况下不是,因为无法将参数传递给过滤器调用。

  • 如果功能需要经常可变重复,并且与模板相关:构建自定义模板标记或过滤器(可以接受参数)。
  • 如果它是特定于 View 的功能,请将其编码到 View 中。
  • 如果多个 View 的功能相同,请在干燥的地方构建该功能。

对于#3,有太多因素决定此代码应该放在哪里,因此没有通用的解决方案。您可以将函数导入到您的 View 中吗?使用模型管理器?模型实例方法?上下文处理器?等等

Could you write a custom Model Manager to do this, so that _set will only ever return objects for the current year? Or is there some other way?

看起来您实际上只需使用反向相关模型的模型管理器即可。

class RoomManager(models.Manager):
    def current_year(self):
        return self.get_queryset().filter(year=datetime.date.today().year)

for room in site.room_set.current_year():
   ...

或者仅在父模型上:

class Site(models.Model):
    ...
    def year_room_set(self):
        return self.room_set.filter(year=datetime.date.today().year)

关于Django - 过滤模板中的RelatedManager _set?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7976347/

相关文章:

Django 管理预览

python - Django 管理员添加自定义过滤器

templates - 谷歌计算引擎: How to change instance template

ios - 如果我再次单击同一个按钮,我将尝试撤消筛选结果

elasticsearch - 如何在 ElasticSearch 中按字段值过滤?

django - 使用 Apache WSGI 通过 DJANGO_SETTINGS_MODULE 环境变量设置 Django 设置文件

python - 更改默认的 auth_user 表名

C++ 在模板的参数中传递模板的构造函数值

c++ - 为 T 类型的容器专门化一个模板

elasticsearch - Logstash kibana geoip 过滤器冲突