Django最佳做法与外键查询 [英] Django best practice with foreign key queries

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

问题描述

models.py

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.

为了防止多个查询,您实际上必须在您的视图中完成与模板中相同的操作,即迭代 SubCatergory ,在python中拉取ID,并将每个ID集合分配到类别上的属性。

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.

我不知道这个答案。

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

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