built - django template object



減少django中的db查詢 (2)

我有一個觀點,通過電影信用數據庫進行搜索,並轉換並返回結果,

# 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 %}

為什麼和這個視圖在哪裡創建這麼多的分貝查詢? 如何以及在哪種方式下,我可以使這個視圖功能更有效/更好? 謝謝。


您將需要查看select_related()( https://docs.djangoproject.com/en/1.3/ref/models/querysets/#select-related )來解決您的查詢洩漏問題。 如果您事先知道您將要查看外鍵相關模型的數據,您將需要添加select_related。 更好的是,如果你知道它只是一些外鍵,你可以只添加你需要的外鍵。

只要你看到django運行的查詢數量超出你的預期,select_related幾乎總是正確的答案






django-views