我是 django 的新手,我已经熬了半夜,试图弄清楚为什么这个视图运行两个 sql 查询,每个查询用于配置文件和点。根据 Django 调试工具,运行了 7 个 SQL 查询。
1. SELECT...profile
2. SELECT...points
3. SELECT...profile
4. SELECT...points
5. SELECT...django_session
6. SELECT...auth_user
7. SELECT...posts
我不明白为什么配置文件和积分被击中两次?每个时间配置文件被命中和每个时间点被命中的 SQL 堆栈跟踪都是相同的:
配置文件的 SQL 堆栈跟踪:
1./Library/Python/2.7/site-packages/django/contrib/staticfiles/handlers.py in call (72) return self.application(environ, start_response)
点的 SQL 堆栈跟踪:
- /Library/Python/2.7/site-packages/django/contrib/staticfiles/handlers.py in call (72) return self.application(environ, start_response)
- /Users/jcarnegie/Documents/web/admin-site/userProfile/views.py in get_context_data(19) context["points"] = Points.objects.get(user_id = self.kwargs["pk"])
这是我的代码:
class UserProfile(generic.DetailView):
template_name = 'userProfile/story.html'
model = Profile
context_object_name = 'profile'
def get_context_data(self, **kwargs):
context = super(UserProfile, self).get_context_data(**kwargs)
context["points"] = Points.objects.get(user_id = self.kwargs["pk"])
context["posts"] = Posts.objects.filter(user_id = self.kwargs["pk"]).prefetch_related('tags')
这是我的模板:
{% extends "core/base.html" %}
{% load url from future %}
{% block content %}
<div class="content">
<div class="content-inner">
<div class="story">
<div class="story-left" id="left-story">
<div class="img">
<div>
<img src="https://s3.amazonaws.com/pic-3123/{{profile.pic}}" />
</div>
</div>
<h1>{{ profile.fname }} {{ profile.lname }}</h1>
<p>{{ profile.title }}</p>
<div class="details">
<div>
<span>Points</span>
<p>{{ points.total }}</p>
</div>
{% if profile.city and profile.state %}
<div>
<span><i class="icon-map-marker"></i></span>
<p>{{ profile.city }}, {{ profile.state }}</p>
</div>
{% endif %}
{% if profile.company %}
<div>
<span><i class="icon-briefcase"></i></span>
<p>{{ profile.company }}</p>
</div>
{% endif %}
<div>
<span><i class="icon-time"></i></span>
<p><span class="muted">Joined on</span> {{ profile.dateJoined|date:"M d, Y" }}</p>
</div>
</div>
</div>
<div class="story-right">
<h3>Posts Made</h3>
<div class="tab-content">
{% if posts %}
<ul id="contributionHolder" class="right-ul">
{% for post in posts %}
<li class="content-item" id="post_{{post.id}}">
<h1 class="volk-font"><a href="{% url 'contributions:detail' post.url post.id %}">{{post.title}}</a></h1>
<p class="volk-font limited-text">{{ post.description }}</p>
<div class="tag-holder">
{% for tag in post.tags.all %}
<a class="tag volk-font grey-button-flat" href="">{{tag.name}} </a>
{% endfor %}
</div>
</li>
{% endfor %}
</ul>
{% else %}
<div class="alert"> <button type="button" class="close" data-dismiss="alert">×</button>{{ profile.fname }} has not made any posts.</div>
{% endif %}
</div>
</div>
</div>
</div>
</div>
{% endblock %}
任何帮助或想法将不胜感激!提前致谢。