Fish
Fish

Reputation: 225

Need to extract the first letter of each item in a queryset and pass it to template

I am passing the variable "first_letter" to a view and want to compare this letter to the first letter of each item returned from a query. I can't get to the point where I have a list to compare to, I only get one item returned.

Model:

class Subjects(models.Model)
    subject = models.CharField(max_length=75)
    ....

View:

def subjects_by_letter(request, first_letter):
    subject_list = Subjects.objects.all()
    for item in subject_list:
        letter = item.subject[0]

        return render_to_response('/path/to/mytemplate.html', {
            'subject_list': subject_list,
            'first_letter': first_letter,
            'letter': letter,
        })

With this in the view what I am getting is the first letter of the last record in the query only:

...
for item in subject_list:
    letter = item.subject[0]
...

eg: if I have subjects entries of "Apple", "Banana" & "Cucumber" it will return just C instead of a list containing A, B & C.

I was hoping someone could pinpoint what simple thing I am missing. Thanks.

Upvotes: 1

Views: 239

Answers (1)

falsetru
falsetru

Reputation: 368954

The code in the question returns inside for loop. You need to create a list outside the list and append the first characters inside the loop.

Or using list comprehension:

def subjects_by_letter(request, first_letter):
    subject_list = Subjects.objects.all()
    letter = [item.subject[0] for item in subject_list]  # <---
    return render_to_response('/path/to/mytemplate.html', {
        'subject_list': subject_list,
        'first_letter': first_letter,
        'letter': letter,
    })

Upvotes: 1

Related Questions