【问题标题】:add custom field to each object in ListView为 ListView 中的每个对象添加自定义字段
【发布时间】:2017-09-07 08:41:14
【问题描述】:

我正在尝试将自定义字段添加到 ListView 以更详细地描述实体(以便我可以在模板中使用它),但令人惊讶的是找不到直接的方法来做到这一点。如何向列表中的 each 对象添加上下文? self.object_list 返回整个列表,并且迭代它以添加这个额外的字段感觉违反直觉。

这是代码的简化版本:

class AreaWiseSchoolsView(ListView):

    template_name = 'search/area.html'
    paginate_by = 15

    def get_queryset(self):
        qs = School.objects.filter(area__name=self.kwargs['areaname'])
        return qs 

    def get_context_data(self, **kwargs):
        school_type_description = ""
        context = super(AreaWiseSchoolsView, self).get_context_data(**kwargs)
        # need code here to add the custom field to each object in the list
        # school = self.something 
        # if school.area.filter(pk=9).exists(): 
        #    school_type_description = "Some description for Area 9"
        # elif school.school_type == 'ND':
        #    school_type_description = "Some description for ND"
        # elif school.school_type == 'MA':
        #     org_type_description = "Some description for MA"
        context['school_type_description'] = school_type_description
        return context

在模板中,我需要能够做到以下几点:

{% for school in object_list %}
    {{school.school_type_description}}
{% endfor %}

另外,是否有更简单的方法来执行上述操作而不是覆盖 get_context_data()?

【问题讨论】:

  • 这种事情最好作为 School 模型本身的方法来完成。

标签: django django-views django-class-based-views


【解决方案1】:

您可以在School 模型中添加@property

from django.db import models


class School(models.Model):
    # ...

    @property
    def type_description(self):
        school_type_description = 'Some default description'

        if self.area.filter(pk=9).exists(): 
            school_type_description = "Some description for Area 9"
        elif self.school_type == 'ND':
            school_type_description = "Some description for ND"
        elif self.school_type == 'MA':
            school_type_description = "Some description for MA"

        return school_type_description

然后你就可以在你的模板中直接访问这个属性了:

{% for school in object_list %}
    {{ school.type_description }}
{% endfor %}

现在不需要在你的ListView 中实现get_context_data()

【讨论】:

  • 感谢@wencakisa 的提示。即使我不在模型中使用@property 装饰器,它也可以在模板中使用(可能是因为该方法没有参数)
【解决方案2】:

您能否为您的学校模型添加属性:

class School(models.Model):
    # YOU DESCRIPTION HERE

    @property
    def school_type_description(self):
        if self.area.filter(pk=9).exists():
            return "Some description for Area 9"
        elif self.school_type == 'ND':
            return "Some description for ND"
        elif self.school_type == 'MA':
            return "Some description for MA"
       return ''

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-10
    • 1970-01-01
    • 1970-01-01
    • 2020-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多