2017-09-13 8 views
0

例でSQLクエリを接続:Djangoはフィルタ

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によってソートされたテーブル内のすべての部屋をしたいです。私は各部屋のために印刷したい データ: Room.locked、ルーム: Building.number、Building.color、Building.name、Floor.wall_color、Room.last_cleaning

さらに私は、オプションのフィルタを許可します。 last_cleaning、Floor.wall_color、Building.number、Building.color

1つのテーブルでは問題はありませんが、3つのテーブルでこれをどのようにアーカイブするか分かりません。

kwargs = {'number': 123} 
kwargs['color'] = 'blue' 
all_buildings = Building.objects.filter(**kwargs).order_by('-number') 

お手伝いできますか?生のSQLクエリを書く必要がありますか?これをDjangoモデルクエリAPIでアーカイブすることはできますか?

私はPostgreSQLで最新のDjangoバージョンを使用しています。

答えて

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) 
関連する問題