Django QuerySet union()没有给出想要的输出

jtw3ybtb  于 2023-06-25  发布在  Go
关注(0)|答案(3)|浏览(119)

我写了下面的代码
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,但我希望它包含时隙列表。
有人能告诉我我做错了什么吗?

smdnsysy

smdnsysy1#

如果我没记错的话,你必须加上all=True:

time_slot_list.union(time_slot, all=True)
  • UNION运算符默认情况下只选择不同的值。若要允许重复值,请使用all=True参数。*

参见https://docs.djangoproject.com/en/4.2/ref/models/querysets/#union

r1wp621o

r1wp621o2#

QuerySet方法不会改变示例,因此您需要将.union()的结果重新分配回变量。
此外,.union()接受另一个QuerySet,而不是模型对象。

# for time_slot in time_slots:                     # Change these
#     time_slot_list.union(time_slot)              #
time_slot_list = time_slot_list.union(time_slots)  # to this
0g0grzrc

0g0grzrc3#

我根本不相信你需要union。你可以在这里使用**__in**查找[Django-doc]:

room_list = Room.objects.all()
time_slot_list = TimeSlot.objects.filter(room__in=room_list)

相关问题