我写了下面的代码
views.py
room_list = Room.objects.all()
time_slot_list = TimeSlot.objects.none()
for room in room_list:
time_slots = TimeSlot.objects.filter(room=room)
for time_slot in time_slots:
time_slot_list.union(time_slot)
print(time_slot_list)
models.py
class Room(models.Model):
class Meta:
ordering = ['number']
number = models.PositiveSmallIntegerField(
validators=[MaxValueValidator(550), MinValueValidator(1)],
primary_key=True
)
CATEGORIES = (
('Regular', 'Regular'),
('Executive', 'Executive'),
('Deluxe', 'Deluxe'),
)
category = models.CharField(max_length=9, choices=CATEGORIES, default='Regular')
CAPACITY = (
(1, '1'),
(2, '2'),
(3, '3'),
(4, '4'),
)
capacity = models.PositiveSmallIntegerField(
choices=CAPACITY, default=2
)
advance = models.PositiveSmallIntegerField(default=10)
manager = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE
)
class TimeSlot(models.Model):
class Meta:
ordering = ['available_from']
room = models.ForeignKey(Room, on_delete=models.CASCADE)
available_from = models.TimeField()
available_till = models.TimeField()
当我打印time_slot_list
时,我得到的是空的QuerySet,但我希望它包含时隙列表。
有人能告诉我我做错了什么吗?
3条答案
按热度按时间smdnsysy1#
如果我没记错的话,你必须加上all=True:
参见https://docs.djangoproject.com/en/4.2/ref/models/querysets/#union
r1wp621o2#
QuerySet
方法不会改变示例,因此您需要将.union()
的结果重新分配回变量。此外,
.union()
接受另一个QuerySet
,而不是模型对象。0g0grzrc3#
我根本不相信你需要
union
。你可以在这里使用**__in
**查找[Django-doc]: