Django将SQL查询与过滤器连接起来

时间:2017-09-13 06:55:56

标签: django postgresql

示例:

class Room(models.Model):
    assigned_floor = models.ForeignKey(Floor, null=True, on_delete=models.CASCADE)
    room_nr = models.CharField(db_index=True, max_length=4, unique=True, null=True)
    locked = models.BooleanField(db_index=True, default=False)
    last_cleaning = models.DateTimeField(db_index=True, auto_now_add=True, null=True)
    ...


class Floor(models.Model):
    assigned_building = models.ForeignKey(Building, on_delete=models.CASCADE)
    wall_color = models.CharField(db_index=True, max_length=255, blank=True, null=True)
    ...


class Building(models.Model):
    name = models.CharField(db_index=True, max_length=255, unique=True, null=True)
    number = models.PositiveIntegerField(db_index=True)
    color = models.CharField(db_index=True, max_length=255, null=True)
    ...

我想输出按Building.number排序的表格中的所有房间。 我想为每个房间打印的数据: Building.number,Building.color,Building.name,Floor.wall_color,Room.last_cleaning

此外,我想允许可选的过滤器: Room.locked,Room.last_cleaning,Floor.wall_color,Building.number,Building.color

有一张桌子对我来说没问题,但我不知道如何用三张桌子存档。

kwargs = {'number': 123}
kwargs['color'] = 'blue'
all_buildings = Building.objects.filter(**kwargs).order_by('-number')
你能帮帮我吗?我是否需要编写原始SQL查询,还是可以使用Django模型查询API将其归档?

我使用最新的Django版本和PostgreSQL。

1 个答案:

答案 0 :(得分:1)

不需要原始SQL:

room_queryset = Room.objects.filter(assigned_floor__wall_color='blue')
                                                  ^^
# A double unterscore declares the following attribute to be a field of the object referenced in the foregoing foreign key field.

for room in room_queryset:
    print(room.assigned_floor.assigned_building.number)
    print(room.assigned_floor.assigned_building.color)
    print(room.assigned_floor.assigned_building.name)
    print(room.assigned_floor.wall_color)
    print(room.last_cleaning)
相关问题