user1428660
user1428660

Reputation:

Rendering to different template after checking length of list

Pretty much a newbie when it comes to both Django and Python. Would appreciate some suggestions here. I did search for similar questions, but couldn't find one that solved my problem.

This is a view that I have written. The intended behaviour is to check the length of a list (districts list), and render to one template if there is only one object in that list, and to another if there are more than one. If there are no objects in the list, 404 is automatically raised.

    @never_cache
def district_list(request, county_slug):
    districts_list = get_list_or_404(NeigbourhoodPostcodeDistrict, county__slug=county_slug)
    if districts_list.count() == 1:
        context = {
        'districts_list': districts_list,
        }
        return render_to_response('neighbourhood/neighbourhood.html',context,context_instance=RequestContext(request))
    else:
        context = {
            'districts_list': districts_list,
        }
        return render_to_response('neighbourhood/district-list.html',context,context_instance=RequestContext(request))

Any help would be much appreciated

Upvotes: 0

Views: 85

Answers (1)

Gareth Latty
Gareth Latty

Reputation: 89017

You are looking for the len() builtin.

E.g:

if len(districts_list) == 1:
    ...

The seq.count() method counts the number of times an individual element occurs in the sequence, and requires one argument (the element to count).

Upvotes: 4

Related Questions