Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Django使用过滤器连接SQL查询_Django_Postgresql - Fatal编程技术网

Django使用过滤器连接SQL查询

Django使用过滤器连接SQL查询,django,postgresql,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, defau

例如:

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排序的所有房间。 我要为每个房间打印的数据: 建筑物.编号,建筑物.颜色,建筑物.名称,地板.墙壁颜色,房间.最后一次清洁

此外,我希望允许可选过滤器: 房间。上锁,房间。最后一次清洁,地板。墙壁颜色,建筑。编号,建筑。颜色

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

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

我在PostgreSQL中使用最新的Django版本。

无需原始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)