将自定义字段添加到ListView中的每个对象

时间:2017-09-07 08:41:14

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

我正在尝试向ListView添加一个自定义字段来更详细地描述一个实体(以便我可以在模板中使用它),但令人惊讶的是找不到直接的方法来做到这一点。如何向列表中的每个对象添加上下文? 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()?

2 个答案:

答案 0 :(得分:2)

您可以在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 %}

现在无需在get_context_data()中实施ListView

答案 1 :(得分:0)

可以为学校模型添加属性:

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 ''