我正在使用Django ORM來處理我的數據庫查詢。我有以下的數據庫表:Django高級查詢
- 資源
- resource_pool
- resource_pool_elem
- 預訂
及以下車型:
class Resource(models.Model):
name = models.CharField(max_length=200)
class Reservation(models.Model):
pass
class ResourcePool(models.Model):
reservation = models.ForeignKey(Reservation, related_name="pools", db_column="reservation")
resources = models.ManyToManyField(Resource, through="ResourcePoolElem")
mode = models.IntegerField()
class ResourcePoolElem(models.Model):
resPool = models.ForeignKey(ResourcePool)
resource = models.ForeignKey(Resource)
目前,我需要查詢在一組rese中使用的資源rvations。我用下面的查詢:
resourcesNames = []
reservations = []
resources = models.Resource.objects.filter(
name__in=resourcesNames, resPool__reservation__in=reservations).all()
,我認爲比賽對類似這樣的一個SQL查詢:
select *
from resource r join resource_pool rp join resource_pool_elem rpe join reservation reserv
where r.id = rpe.resource and
rpe.pool = rp.id and
reserv.id = rp.reservation and
r.name in (resourcesNames[0], ..., resourcesNames[n-1])
reserv.id in (reservations[0], ..., reservations[n-1])
現在,我想一個限制添加到該查詢。每個池可能有一個獨佔模式布爾標誌。將有一個額外的輸入列表,每個池請求的獨佔標誌,我只想查詢獨佔標誌匹配請求的專有標誌,如果exclusive = true或獨佔標誌爲false的池的資源的資源。我可以使用Python構建SQL查詢,其代碼類似於:
query = "select *
from resource r join resource_pool rp join resource_pool_elem rep
join reservation reserv
where r.id = rpe.resource and
rpe.pool = rp.id and
reserv.id = rp.reservation and
reserv.id in (reservations[0], ..., reservations[n-1]) and ("
for i in resourcesNames[0:len(resourcesNames)]
if i > 0:
query += " or "
query += "r.name = " + resourcesNames[i]
if (exclusive[i])
query += " and p.mode == 0"
query += ")"
有沒有一種方法可以在Django查詢中表達這個sql查詢?