python - 需要提取查询集中每个项目的首字母并将其传递给模板

标签 python django django-views

我将变量“first_letter”传递给 View ,并希望将此字母与查询返回的每个项目的第一个字母进行比较。我无法达到可以比较的列表的地步,我只返回了一项。

型号:

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

查看:

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,
        })

在 View 中,我得到的只是查询中最后一条记录的第一个字母:

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

例如:如果我有“Apple”、“Banana”和“Cucumber”的主题条目,它将仅返回 C,而不是包含 A、B 和 C 的列表。

我希望有人能指出我错过了什么简单的事情。谢谢。

最佳答案

问题中的代码在 for 循环内返回。您需要在列表外部创建一个列表,并将第一个字符附加到循环内。

或者使用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,
    })

关于python - 需要提取查询集中每个项目的首字母并将其传递给模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43289004/

相关文章:

Linux 中的 Python 脚本

python - Django Charfield null=未引发 False 完整性错误

django - 通过 django 跟踪打开的电子邮件

python - IndexError : Dimension out of range (expected to be in range of [-1, 0],但得到 1)

python - 在 .tcshrc 文件中将 Anaconda 设置为默认 Python

python - 如何使用 Django 检索多个查询参数值?

python - 为两个模型创建 View

python - 在过滤器内的模型字段中按间隔增加日期的月份

python - 添加要在 tkinter 中显示的变量

python - 合并 Json 响应 Django python