2012-05-02 7 views
1

jQuery 테이블리스트를 사용하고 있으므로 뷰에 Person.objects.all()을 사용하기 때문에 페이지 매김을 원하지 않는 많은 양의 데이터를 표시해야합니다. 로드 시간이 너무 오래 걸리므로 원시 SQL을 수행하려고합니다.원시 SQL을 장고 템플릿에 전달하기

Django의 일반적인보기를 사용해 보았지만 objects.all() 메서드와 마찬가지로 느립니다.

여기 내 모델입니다. 본질적으로, 나는 모든 사람들을 얼마나 자주 등장했는지, 예를 들어 var1 또는 var2과 같이 표시하고 싶습니다.

class Person(models.Model): 
    name = models.CharField(max_length=64, blank=True, null=True) 
    last_name = models.CharField(max_length=64,) 
    slug = models.SlugField() 

class Object(models.Model): 
    title = models.ForeignKey(Title) 
    number = models.CharField(max_length=20) 
    var1 = models.ManyToManyField(Person, related_name="var1_apps", blank=True, null=True) 
    var2 = models.ManyToManyField(Person, related_name="var2_apps", blank=True, null=True) 
    var3 = models.ManyToManyField(Person, related_name="var3_apps", blank=True, null=True) 
    # ... 
    slug = models.SlugField() 

from django.db import connection 
    def test (request): 
     cursor = connection.cursor() 
     cursor.execute('SELECT * FROM objects_person') 
     persons = cursor.fetchall() # fetchall() may not be the right call here? 
     return render_to_response('test.html', {'persons':persons}, context_instance=RequestContext(request)) 

템플릿 : 그것은 빈 줄을 반복하지만, 난 그냥 {{ creator }}를 호출하는 경우는 전체 SQL 테이블을 보여줍니다 무엇을

  <table class="table tablesorter"> 
       <thead> 
        <tr> 
        <th>Name</th> 
        <th>Var1</th> 
        <th>Var2</th> 
        <th>Var3</th> 
        </tr> 
       </thead> 
       <tbody> 
         {% for person in persons %} 
        <tr> 
         <td><a href="{{ person.get_absolute_url }}">{{ person.last_name }}{% if person.name %}, {{ person.name }}{% endif %}</a></td> 
         <td>{{ person.var1_apps.count }}</td> 
         <td>{{ person.var2_apps.count }}</td> 
         <td>{{ person.var3_apps.count }}</td> 
        </tr> 
       {% endfor %} 
       </tbody> 
      </table> 

- 내가 원하지 않는. 쿼리에 문제가있을 것입니다. 따라서 도움을 얻을 수 있습니다.

+2

놀랍지 만,'.all()'은 정확히'SELECT * FROM ... '(귀하의 경우)로 번역됩니다. 그래서 나는 당신이 무엇을하려고하는지 이해하지 못합니다. 당신은 지금은 아무 것도 최적화하지 않습니다. – DrTyrsa

답변

3

문제는 Person.objects.all()이 아닙니다. 해당 쿼리 세트를 반복 할 때 에 대해 세 개의 쿼리를 수행하면 카운트를 계산할 쿼리 세트의 각 항목이 개입니다.

대답은 annotate입니다. 각 필드의 개수가 포함 된 쿼리 세트입니다.

# in the view 
persons = Person.objects.annotate(num_var1_apps=Count('var1_apps'), 
            num_var2_apps=Count('var2_apps'), 
            num_var3_apps=Count('var3_apps'), 
           ) 

# in the template 
{% for person in persons %} 
       <tr> 
        <td><a href="{{ person.get_absolute_url }}">{{ person.last_name }}{% if person.name %}, {{ person.name }}{% endif %}</a></td> 
        <td>{{ person.num_var1_apps }}</td> 
        <td>{{ person.num_var2_apps }}</td> 
        <td>{{ person.num_var3_apps }}</td> 
       </tr> 
{% end for %} 
+0

아, 훨씬 빠릅니다. 이제는 비정상적으로 높은 숫자를 보여 주므로 그 점이 무엇인지 잘 모르겠습니다. – AAA

+0

아,'Count = '에'distinct = True'를 추가해야했습니다 (그러나 내가 추가 한 후 눈에 띄게 느린 것 같습니다). 감사! – AAA

관련 문제