您好我正在尝试创建一个使用模型项的页面,其中包含一个名为 data_type 的模型字段,其整数选项选择为1或2.我目前有一个Listview页面,我试图创建两个列表,一个显示data_type = 1的项目,另一个显示data_type = 2。
1代表模型,2代表脚本,如果有帮助吗?
这是我的views.py
class ItemListView(generic.ListView):
context_object_name = 'model_list'
queryset = Item.objects.filter(data_type='1')
context_object_name = 'script_list'
queryset = Item.objects.filter(data_type='2')
template_name = 'item_list.html',
Item_list.html
<h3 class="text-muted text-center mt-4">Models</h3>
<hr>
<div class="container">
<div class="row mt-4">
{% if model_list %}
{% for item in model_list %}
<div class="col-md-3">
<div class="card card-primary card-effects p-2 mb-3 mt-4">
<a href="{% url 'portal:item_detail' item.pk %}" class="card-full-link">
<img class="card-img" src="{{ item.image.url }}" alt="Generic placeholder image" width="225" height="185">
<div class="card-body">
<p class="text-muted"> {{ item.get_data_type_display }}</p>
<h4 class="text-left"> {{ item.name }}<span class="text-blue">Ξ{{ item.price }}</span></h4>
</div>
</a>
<!-- <p><a class="btn btn-success" href="#" role="button">Learn more »</a></p> !-->
</div>
</div>
{% endfor %}
{% else %}
<p>There are no items in the database.</p>
{% endif %}
</div>
</div>
<h3 class="text-muted text-center mt-4">Scripts </h3>
<hr>
<div class="container">
<div class="row mt-4">
{% if script_list %}
{% for item in script_list %}
<div class="col-md-3">
<div class="card card-primary card-effects p-2 mb-3 mt-4">
<a href="{% url 'portal:item_detail' item.pk %}" class="card-full-link">
<img class="card-img" src="{{ item.image.url }}" alt="Generic placeholder image" width="225" height="185">
<div class="card-body">
<p class="text-muted"> {{ item.get_data_type_display }}</p>
<h4 class="text-center"> {{ item.name }}<span class="text-blue">Ξ{{ item.price }}</span></h4>
</div>
</a>
<!-- <p><a class="btn btn-success" href="#" role="button">Learn more »</a></p> !-->
</div>
</div>
{% endfor %}
{% else %}
<p>There are no items in the database.</p>
{% endif %}
</div>
</div>
希望views.py会让你知道我想要做什么。看来我不能有两个context_object_name和querysets。如果我删除了vottom context_object_name和queryset,则将加载model_list。
我从django docs https://docs.djangoproject.com/en/2.0/topics/class-based-views/generic-display/获得了context_object_name查询集的想法
答案 0 :(得分:1)
您可以覆盖get_context_data
方法:
class ItemListView(generic.ListView):
context_object_name = 'model_list'
queryset = Item.objects.filter(data_type='1')
template_name = 'item_list.html'
def get_context_data(self, **kwargs):
context = super(ItemListView, self).get_context_data(**kwargs)
context['script_list'] = Item.objects.filter(data_type='2')
return context