简体   繁体   English

模板中的Django过滤器related_name子集

[英]Django filter related_name subset in templates

I have a foreign key and I'm using the related_name field like so: 我有一个外键,并且正在使用related_name字段,如下所示:

class Pizza(models.Model):
   ...
   restaurant = models.ForeignKey('Restaurant', related_name='pizzas_offered')
   active = models.BooleanField(...)
   ...

Example from the view: 视图中的示例:

my_restaurant = get_object_or_404(Restaurant, pk=id)

In any template I can run something like my_restaurant.pizzas_offered.all to get all the pizzas belonging to a particular restaurant. 在任何模板中,我都可以运行类似my_restaurant.pizzas_offered.all的东西,以获得属于特定餐厅的所有比萨饼。 However, I only want the pizzas that are active (active=True). 但是,我只想要激活的比萨饼(有效=真)。 Is there a way to retrieve this subset in the template, without having to pass a separate variable in the view? 有没有一种方法可以检索模板中的此子集,而不必在视图中传递单独的变量? Please note that I always want to only show the active pizzas only so if I have to make a change in the model to make this happen, that is fine too. 请注意,我始终只希望仅显示活动中的比萨饼,因此,如果我必须对模型进行更改以使这种情况发生,那也可以。

NOTE: in the view I can simply pass my_restaurant.pizzas_offered.filter(active=True) but it returns an error when I use it in the template: 注意:在视图中,我可以简单地传递my_restaurant.pizzas_offered.filter(active = True),但是在模板中使用它时会返回错误:

{% for details in my_restaurant.pizzas_offered.filter(active=True) %}
  {{ details.name }}
{% endfor %}

It returns this error: Could not parse the remainder: '(active=True)' 它返回此错误: 无法解析余数:'(active = True)'

There are some reasons why I want to do this on template level and not in the view (main reason: I often loop through all the records in the database and not just one restaurant, so I can't just query for the one record). 有一些原因我想在模板级别而不是在视图中执行此操作(主要原因:我经常遍历数据库中的所有记录而不仅仅是一个餐厅,所以我不能只查询一个记录) 。 So my question is how to do this on template-level. 所以我的问题是如何在模板级别执行此操作。

You need to create a Manager for your Pizza model and set the Meta.base_manager_name : 您需要为您的Pizza模型创建一个Manager并设置Meta.base_manager_name

class PizzaManager(models.Manager):
    def active(self):
        return self.filter(status=True)

class Pizza(models.Model):
    ...
    objects = PizzaManager()

    class meta:
        base_manager_name = 'objects'

Now you can use the method active in your template: 现在,您可以在模板中使用active方法:

{% for details in my_restaurant.pizzas_offered.active %}
    ...
{% endfor %}

For more information you can read the documentation about Default and Base managers . 有关更多信息,您可以阅读有关默认和基本管理器的文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM