我需要将两个查询集合并到一个查询集中(结果不能是列表或其他类型的对象),因为当我在模板中迭代查询集时,我需要访问它们的关系,这不能从列表或字典中完成。
我尝试过像union这样的解决方案但是这是不可接受的,因为我需要访问模板中的关系。
我需要数据结构的循环看起来像下面的循环。这个对象的两个关系是用户和飞机。
{% for key in active %}
<tr>
<td>{{key.user.name}}</td>
<td>{{key.aircraft.tail_number}}</td>
<td>{{key.departure_date}}</td>
<td>{{key.departure_city|title}}</td>
<td>{{key.arrival_city|title}}</td>
</tr>
{% endfor %}
楷模:
class HaveTrip(models.Model):
# fields are null by default
departure_date = models.DateField()
arrival_date = models.DateField()
departure_time = models.TimeField()
arrival_time = models.TimeField()
departure_city = models.CharField(max_length=100)
departure_code = models.CharField(max_length=100)
arrival_city = models.CharField(max_length=100)
arrival_code = models.CharField(max_length=100)
trip_notes = models.CharField(max_length=500)
occupied_seats = models.IntegerField()
extra_seats = models.IntegerField()
booking_exp = models.IntegerField()
created = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(
'users.User',
related_name='have_trip',
unique=False,
on_delete=models.CASCADE
)
aircraft = models.ForeignKey(
'aircraft.Aircraft',
related_name='trip',
unique=False,
on_delete=models.CASCADE
)
approved = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
class NeedTrip(models.Model):
# fields are null by default
departure_date = models.DateTimeField()
arrival_date = models.DateField()
departure_time = models.DateTimeField()
arrival_time = models.DateTimeField()
departure_city = models.CharField(max_length=100)
departure_code = models.CharField(max_length=100)
arrival_city = models.CharField(max_length=100)
arrival_code = models.CharField(max_length=100)
trip_notes = models.CharField(max_length=500)
primary_guest_passenger = models.CharField(max_length=100)
preferred_category = models.CharField(max_length=100)
seats_max = models.IntegerField()
seats_min = models.IntegerField()
user = models.ForeignKey(
'users.User',
related_name='need_trip',
unique=False,
on_delete=models.CASCADE
)
approved = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
一种想法是以某种方式在两个表之间以一种返回查询集的方式进行连接,但是此时我一直无法弄清楚如何做到这一点。我还没有尝试过原始SQL,所以也许这就是路线?
我不认为可以组合不同模型的查询集。我只想使用itertools。
from itertools import chain
active = list(chain(queryset1, queryset2))