我正在使用 Django ORM 来处理我的数据库查询。我有以下数据库表:
- 资源
- 资源池
- 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)
目前,我需要查询一组预留中使用的资源。我使用以下查询:
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])
现在,我想为这个查询添加一个限制。每个池可能有一个独占模式布尔标志。将有一个额外的输入列表,其中包含每个池的请求的独占标志,如果独占 = true 或独占标志为假的池的资源,我只想查询独占标志与请求的独占标志匹配的池的资源。我可以使用 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 查询?