减少django中的db查询

时间:2011-06-28 22:22:17

标签: django django-models django-templates django-views

我有一个视图,搜索电影信用数据库,并转换并返回结果 -

# From the following results:
Avatar - James Cameron - director
Avatar - James Cameron - writer
Avatar - James Cameron - editor
Avatar - Julie Jones - writer
Crash - John Smith - director

# ...display in the template as:
Avatar - James Cameron (director, writer, editor)
Avatar - Julie Jones (writer)
Crash - John Smith (director)

但是,当我执行此转换并执行print connection.queries时,我正在访问数据库大约100次。这是我目前的情况 -

# in models
class VideoCredit(models.Model):
    video = models.ForeignKey(VideoInfo)

    # if the credit is a current user, FK to his profile,
    profile = models.ForeignKey('UserProfile', blank=True, null=True)
    # else, just add his name
    name = models.CharField(max_length=100, blank=True)
    # normalize name for easier searching / pulling of name
    normalized_name = models.CharField(max_length=100)

    position = models.ForeignKey(Position)
    timestamp = models.DateTimeField(auto_now_add=True)
    actor_role = models.CharField(max_length=50, blank=True)    

class VideoInfo(models.Model):
    title = models.CharField(max_length=256, blank=True)
    uploaded_by = models.ForeignKey('UserProfile')
    ...

类Position(models.Model):     position = models.CharField(max_length = 100)     ordering = models.IntegerField(max_length = 3)

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
        ...

在我看来,我正在以(name, video, [list_of_positions])的形式构建一个三元组列表,用于显示学分 -

    credit_set = VideoCredit.objects.filter(***depends on a previous function***)
    list_of_credit_tuples = []
    checklist = [] # I am creating a 'checklist' to see whether to append the positions
                   # list of create a new tuple entry
    for credit in credit_set:
        if credit.profile:  # check to see if the credit has an associated profile
            name = credit.profile    
        else:
            name = credit.normalized_name
        if (credit.normalized_name, credit.video) in checklist:
            list_of_keys = [(name, video) for name, video, positions in list_of_credit_tuples]
            index = list_of_keys.index((name, credit.video))
            list_of_credit_tuples[index][2].append(credit.position)
        else:
            list_of_credit_tuples.append((name, credit.video, [credit.position]))
            checklist.append((credit.normalized_name, credit.video))
    ...

最后,在我的模板中显示学分(注意:如果学分有个人资料,请提供指向用户个人资料的链接) -

{% for name, video, positions in list_of_credit_tuples %}
<p>{% if name.full_name %}
    <a href="{% url profile_main user_id=name.id %}">{{name.full_name}}</a>
    {% else %}
    {{name}}
    {% endif %}
    <a href="{% url videoplayer video_id=video.id %}">{{video}}</a>
    ({% for position in positions %}{% ifchanged %}{{position}}{% endifchanged %}{% if not forloop.last %}, {% endif %}{% endfor %})
{% endfor %}

此视图为何以及在何处创建了如此多的数据库查询?如何以及以何种方式使这个视图功能更有效/更好?谢谢。

2 个答案:

答案 0 :(得分:15)

您需要查看select_related()(https://docs.djangoproject.com/en/1.3/ref/models/querysets/#select-related)以解决查询泄漏问题。如果你提前知道你将要查看外键相关模型的数据,那么你需要添加select_related。更好的是,如果你知道它只是几个外国钥匙,你只能添加你需要的。

任何时候你看到django运行了大量的查询超过你的预期,select_related几乎总是正确的答案

答案 1 :(得分:4)

尝试添加此Django代码段,该代码段会将查询数量以及查询本身返回给您的模板:

http://djangosnippets.org/snippets/159/

这很容易告诉你泄漏源自何处。

相关问题