Django 外键查询最佳实践 [英] Django best practice with foreign key queries

查看:28
本文介绍了Django 外键查询最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

models.py

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

class SubCatergory(models.Model):
    parent_category = models.ForeignKey(Category)
    name = models.CharField(max_length=100)

views.py

def all_products(request):
c = Category.objects.all()
s = SubCatergory.objects.all()

return render_to_response('all_products.html',
                          {'c':c, 's':s})

all_products.html

all_products.html

{% for category in c %}
    <h1>{{ category.name }}</h1>
    <ul>
        {% for sub in s  %}
        {% if category.id == sub.parent_category.id %}
            <li>{{ sub.name }}</li>
        {% endif %}
        {% endfor %}
    </ul>
{% endfor %}

只是想知道以上是否是外键查询的最佳实践.我在模板级别进行过滤(如果 category.id == sub...),我应该将其移至模型或视图级别吗?

Just wondering if above is best practice for foreign key queries. I'm filtering at the template level (if category.id == sub...), should I move this to the model or view level instead?

推荐答案

如果子类别只有一个深度,下面的代码应该没有问题:

If there's only ever one depth of subcategory, the following code shouldn't be a problem:

{% for category in c %}
    <h1>{{ category.name }}</h1>
    <ul>
        {% for sub in category.subcatergory_set.all %}
            <li>{{ sub.name }}</li>
        {% endfor %}
    </ul>
{% endfor %}

但是有一些优化技巧可以减少查询次数,因为您将在每个循环中执行查询.我现在在想一个.

But there are some optimization tricks to reduce query count as you'd be doing a query per loop. I'm trying to think of one now.

实际上,我开始认为这是一个有趣的问题:最佳实践?

Actually, I'm starting to think this is an interesting question: best practice?

您的方法使用 2 个查询.我的方法是使用 django 实践,但会执行多个查询.

Your method uses 2 queries. My method is using django practices, but does multiple queries.

为了防止多次查询,您基本上必须在视图中执行您在模板中所做的相同操作,即迭代 SubCategory,在 python 中提取它们的 ID 并将每个 ID 分组设置为 Category 上的一个属性.

To prevent multiple queries, you'd essentially have to do the same thing you've done in your template in your view, namely iterating over SubCatergory, pulling their IDs in python and grouping each ID set onto an attribute on Category.

我不知道这个问题的答案.

I don't know the answer to this one.

这篇关于Django 外键查询最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆