How can I refactor this django query to not select each individual object?

Here's my view:

def rsvp_list(request, id, template="rsvp/rsvp_list.html"):
    rsvp = RSVP.objects.get(id=id)

    return render_to_response(template, {
        'attendees': rsvp.attendee_set.all().order_by('email__first_name'),
    }, context_instance=RequestContext(request))

and here's my template:

{% for attendee in attendees %}
{{ attendee.email.get_name }}{{ attendee.guests }}
{% endfor %}

When the request is run, the template then runs a query for each attendee to get their first and last name (get name just puts the two together). Here's an example query that django fires from the template:

SELECT `rsvp_email`.`id`, `rsvp_email`.`added`, `rsvp_email`.`first_name`, `rsvp_email`.`last_name`, `rsvp_email`.`address` FROM `rsvp_email` WHERE  `rsvp_email`.`id` = 1038

How can I retrieve the first and last name of each attendee is the first query without looping through it 400 times in the template?


I should have read a bit further in the documentation.

In order to reduce the queries that are going to happen on related object later, just use select_related. So my query becomes:

attendees = rsvp.attendee_set.select_related().all().order_by('email__first_name')
链接地址: http://www.djcxy.com/p/56506.html

上一篇: Django ModelForm外键过滤

下一篇: 我怎样才能重构这个Django查询不选择每个单独的对象?