简体   繁体   English

模型管理器,用于非空记录,包括来自另一个管理器的对象

[英]Model Manager for non-empty records that includes objects from another manager

I have two models with managers: Category and Project. 我有两个与经理一起的模型:“类别”和“项目”。

class PopulatedCategoriesManager(models.Manager):
    def get_query_set(self):
        return super(PopulatedCategoriesManager, self) \
            .get_query_set() \
            .filter(projects__is_published=True).distinct()

class Category(models.Model):
    title = models.CharField(max_length=50)

    class Meta(Orderable.Meta):
        verbose_name_plural = 'Categories'

    objects = models.Manager()
    populated = PopulatedCategoriesManager()

class PublishedProjectsManager(models.Manager):
    def get_query_set(self):
        return super(PublishedProjectsManager, self) \
            .get_query_set().filter(is_published=True)

class Project(models.Model):
    title = models.CharField(max_length=50)
    category = models.ForeignKey(Category, related_name='projects')
    #other fields

    objects = models.Manager()
    published = PublishedProjectsManager()

The PopulatedCategoriesManager works as expected, returning only the Categories that have Projects that are published, but my problem is at the template level. PopulatedCategoriesManager可以按预期工作,仅返回具有已发布项目的类别,但是我的问题是在模板级别。 I'm having trouble accessing only the published projects. 我只能访问已发布的项目。

In the loop, the category instance doesn't know how to access only the published projects, so I'm curious as to what the most efficient way of getting to those objects is? 在循环中,类别实例不知道如何仅访问已发布的项目,因此我很好奇获取这些对象的最有效方法是什么?

I'd love to be able to write... 我很想写...

{% for category in categories %}
    {% for project in category.published_projects.all %}

    {% endfor %}
{% endfor %}

...without making a database call for each category. ...无需为每个类别进行数据库调用。 Can someone please give me some pointers? 有人可以给我一些指示吗? I can write some raw SQL to do this, and I have some ideas from another Stack Overflow post to make this work, but I'd like to solve this at the model level. 我可以编写一些原始的SQL来做到这一点,而我在另一个Stack Overflow帖子中也提出了一些建议,以使这项工作可行,但我想在模型级别解决此问题。

I think your best bet is probably to just query all published_projects, ordered by category_id, then regroup them in the template. 我认为您最好的选择可能是只查询按category_id排序的所有published_projects,然后将它们重新组合到模板中。

projects = Project.published.all().order_by('category_id')

... ...

{% regroup projects by category_id as project_categories %}

{% for category in project_categories %}
    {% for project in category.list %}
        {{ project.title }}
    {% endfor %}
{% endfor %}

You don't show whether you need details of the category as well as just using it as a grouper, but if you do you can add select_related() to the original query. 您不会显示是否需要类别的详细信息以及仅将其用作分组器,但是如果您需要,可以将select_related()添加到原始查询中。

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

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