将附加值附加到Django通用视图中的queryset,然后再提交给temp

2024-04-26 12:32:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下看法:

class AppointmentListView(LoginRequiredMixin, ListView):

    queryset = Appointment.objects.prefetch_related('client','patients')

我需要能够根据以下内容向每个返回的约会对象添加一个额外的变量:

^{pr2}$

值('default'、'primary'等)对应于Bootcamp主题中的标准css类,我想根据约会类型使用这些类。例如,“default”生成灰色按钮,“warning”生成红色按钮等

我需要根据记录的状态将每个约会记录映射到特定的css按钮(“即将到来”将显示“默认”类等)。在

我最初的想法是循环查询集并构建一个单独的数组/字典,将约会pk映射到给定的css类,比如 1:'success', 2:'warning',然后将其作为上下文变量传入。在

但我想知道是否可以直接将值添加到每个约会对象(也许将queryset保存为一个列表?)这将是一个更清洁的解决方案,但不确定应该如何处理。在

有什么好主意吗


Tags: 对象defaultobjects记录按钮cssclassappointment
2条回答

您应该像这样重载ListView的get_queryset方法

def get_queryset(self, **kwargs):
    queryset = super(AppointmentListView, self).get_queryset(**kwargs)
    # Add new elements here
    ...
    return queryset

我通过重写get_queryset()并给对象(即数据库中的每一行)一个额外的动态键/值来实现这一点:

class AppointmentListView(LoginRequiredMixin,ListView):
    #friendly template context
    context_object_name = 'appointments'
    template_name = 'appointments/appointment_list.html'

    def get_queryset(self):
        qs = Appointment.objects.prefetch_related('client','patients')
        for r in qs:
            if r.status == r.STATUS_UPCOMING: r.css_button_class = 'default'
            if r.status == r.STATUS_ARRIVED: r.css_button_class = 'warning'
            if r.status == r.STATUS_IN_CONSULT: r.css_button_class = 'success'
            if r.status == r.STATUS_WAITING_TO_PAY: r.css_button_class = 'danger'
            if r.status == r.STATUS_PAYMENT_COMPLETE: r.css_button_class = 'info'
        return list(qs)

有几件事:

  1. 我将查询集qs转换为列表以“冻结”它。这可以防止重新评估queryset(例如slice),这反过来会导致动态模型更改在从DB中提取新数据时丢失。

  2. 我需要显式地给template_name赋值。重写get_queryset时,模板名称不是自动派生的。作为比较,下面设置了queryset属性的代码会自动生成模板名称:

    class AppointmentListView(LoginRequiredMixin, ListView):
        queryset = Appointment.objects.prefetch_related('client', 'patients')
        #template name FOO_list derived automatically
    
    #appointments/views.py
    ...
    #can use derived name (FOO_list)
    {% for appointment in appointment_list %}
    ...
    

相关问题 更多 >