簡體   English   中英

我可以將2個模型放在Django Views.py的單個類中嗎?

[英]Can I put 2 models in a single class in Django Views.py?

目標:我正在嘗試在模板中顯示來自2個不同表的產品和訂單。 我在如何在views.py的一個類中加入兩個模型方面遇到了困難。

我嘗試過django rest框架,但這不是我的應用程序的范圍。

這是我的代碼:


    class UserDashboardTemplateView(ListView):
        #I want to insert the ORDER model in this class also
        model = Product
        context_object_name = 'product'
        template_name = 'product/dashboard.html'

數據必須以以下格式顯示:


    {% for o in orders %}
          <tr>
              <td>{{ o.status }}</td>
          </tr>
    {% endfor %}

當然ListView只是“糖”,可以方便地從一個地方獲取對象。 您想改為下拉至TemplateView (TemplateViews本身不會進行分頁等;如果需要,則需要您自己進行,或者可能將兩個ListViews組合到一個視圖中)。


class UserDashboardTemplateView(TemplateView):
    # I want to insert the ORDER model in this class also
    model = Product
    context_object_name = "product"
    template_name = "product/dashboard.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['products'] = Product.objects.all()  # or whatever
        context['orders'] = Order.objects.all()  # or whatever
        return context

暫無
暫無

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

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