簡體   English   中英

在移交給模板之前,將附加值附加到Django通用視圖中的queryset

[英]Append additional values to queryset in Django generic views before handing to template

我有以下觀點:

class AppointmentListView(LoginRequiredMixin, ListView):

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

我需要能夠根據以下內容為每個返回的約會對象添加一個額外的變量:

status_choices={
    'STATUS_UPCOMING':'default',
    'STATUS_ARRIVED':'primary',
    'STATUS_IN_CONSULT': 'success',
    'STATUS_WAITING_TO_PAY':'info',
    'STATUS_PAYMENT_COMPLETE':'warning',
}

值(“默認”,“主”等)對應於我想根據約會類型使用的Bootcamp主題中的標准CSS類。 例如,“默認”將產生一個灰色按鈕,“警告”一個紅色按鈕等。

我需要根據記錄的狀態將每個約會記錄映射到某個CSS按鈕(“即將到來”將顯示“默認”類,等等)。

我最初的想法是遍歷查詢集並構建一個單獨的數組/字典,將Appointment pk映射到給定的CSS類,例如1:'success', 2:'warning' ,然后將其作為上下文變量傳入。

但是我想知道是否可以直接將值添加到每個約會對象中(也許將查詢集保存為列表嗎?)這將是一種更簡潔的解決方案,但不確定如何實現。

任何想法表示贊賞

您應該像這樣重載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. 我將queryset qs轉換為一個列表以“凍結”它。 這樣可以防止對查詢集進行重新評估(例如,切片),這又會導致隨着從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 %} ... 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM