型号:
class Technology(models.Model):
name = models.CharField(max_length=100, unique=True)
slug = models.SlugField(max_length=100, unique=True)
class Site(models.Model):
name = models.CharField(max_length=100, unique=True)
slug = models.SlugField(max_length=100, unique=True)
technology = models.ManyToManyField(Technology, blank=True, null=True)
查看:
def portfolio(request, page=1):
sites_list = Site.objects.select_related('technology').only('technology__name', 'name', 'slug',)
return render_to_response('portfolio.html', {'sites':sites_list,}, context_instance=RequestContext(request))
模板:
{% for site in sites %}
<div>
{{ site.name }},
{% for tech in site.technology.all %}
{{ tech.name }}
{% endfor %}
</div>
{% endfor %}
但在该示例中,每个站点都会进行一次额外查询以获取技术列表。有没有办法以某种方式在1个查询中制作它?
答案 0 :(得分:1)
您正在寻找的是进行反向外键查找的有效方法。一般方法是:
qs = MyRelatedObject.objects.all()
obj_dict = dict([(obj.id, obj) for obj in qs])
objects = MyObject.objects.filter(myrelatedobj__in=qs)
relation_dict = {}
for obj in objects:
relation_dict.setdefault(obj.myobject_id, []).append(obj)
for id, related_items in relation_dict.items():
obj_dict[id].related_items = related_items
我刚刚写了一篇博文,你可以在这里找到更多信息:http://bit.ly/ge59D2
答案 1 :(得分:0)
怎么样:
使用Django的session framework;在启动时加载列表request.session['lstTechnology'] = listOfTechnology
。并在应用程序的其余部分使用会话。