![](/img/trans.png)
[英]How can I move data from views.py to a models.py in python/django in this case?
[英]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.