[Django] 合併兩個QuerySet的library: itertools

George
4 min readJan 20, 2019

來源:https://mushfiq.me/2013/08/04/django-merging-to-queryset-using-itertools/

發現到這個方式有助於結合兩個queryset,放在同一張table裡面。

建立django project, app

> django-admin startproject [your_project_name]
> cd [your_project_name]

增加models.py程式碼

# models.py
class Cars(models.Model):
name = models.CharField(max_length=10)
number = models.IntegerField()
color = models.CharField(max_length=5)
class Meta:
managed = True
class Truck(models.Model):
name = models.CharField(max_length=10)
number = models.IntegerField()
size = models.IntegerField()
class Meta:
managed = True

增加templates檔案夾,並在templates底下增加index.html

> mkdir [your_project_name]/templates/
> vim [your_project_name]/templates/index.html

在settings.py設定檔增加

# settings.py
TEMPLATES = [
{
...
'DIRS': [os.path.join(BASE_DIR, 'templates')],
...
}
]
}
]

在 index.html 增加程式碼

<table class="table table-hover">
<thead>
<tr>
<th scope="col">name</th>
<th scope="col">number</th>
<th scope="col">color</th>
<th scope="col">size</th>
</tr>
</thead>
<tbody>
{% for i in all_vechiles %}
<tr>
<td>{{ i.name }}</td>
<td>{{ i.number }}</td>
<td>{{ i.color }}</td>
<td>{{ i.size }}</td>
</tr>
{% endfor %}
</tbody>
</table>

增加views.py程式碼

from django.shortcuts import render
from itertools import chain
from .models import Cars, Truck
def main(request):
template = 'index.html'
cars = Cars.objects.all()
trucks = Truck.objects.all()
all_vechiles = list(chain(cars, trucks))
context = {"all_vechiles": all_vechiles}
return render(request, template, context)

makemigrations & migrate 資料

> python manage.py makemigrations
> python manage.py migrate
> python manage.py runserver

瀏覽器上輸入 http://localhost:8000 會顯示

如果你覺得文章很棒或有幫助到您,不妨幫我點個拍手吧! 謝謝…

--

--