我正在从事一个项目,并且在Django中也很新。我有其中一些联接的sql原始查询。但是我的要求是制作Django orm。我试图做到这一点,但无法为该查询创建准确的订单。
我已经尝试过使django orm成功,但找不到确切结果:
model_data = Model.objects.prefetch_related(
'modelapi', 'modelauth', 'modelapiconfig').filter(
modelauth__retrieval_id='XXYY',modelauth__is_active=True).values(
'model_name',
'modelauth__retrieval_id',
'modelapi__api_endpoint_name',
'modelapi__modelapiconfig__api_config')
这是我的模型。py:
class Model(models.Model):
model_name = models.CharField(max_length=40, blank=False,
verbose_name='Name',
unique=True)
def __str__(self):
return self.model_name
class Meta:
db_table = 'connector_model'
class ModelApi(models.Model):
model_id = models.ForeignKey(Model, on_delete=models.CASCADE,
verbose_name='MODEL Name', related_name='modelapi')
model_description = models.CharField(max_length=150,
verbose_name='API Description')
api_endpoint_name = models.CharField(max_length=100,
blank=False,
verbose_name='API endpoint name', default='')
def __str__(self):
return self.model_id.model_name + "_" + self.api_endpoint_name
class Meta:
db_table = "connector_model_api"
class ModelAuthentication(models.Model):
model_id = models.ForeignKey(Model, on_delete=models.CASCADE,
verbose_name='MODEL Name', related_name='modelauth')
email = models.EmailField(max_length=70)
retrieval_id = models.CharField(max_length=30, blank=False, unique=True)
def __str__(self):
return self.model_id.model_name + "_" + self.retrieval_id
class Meta:
db_table = "connector_model_authentication"
class ModelApiConfig(models.Model):
model_auth = models.ForeignKey(ModelAuthentication, on_delete=models.CASCADE,
verbose_name='MODEL Customer Name')
model_api = models.ForeignKey(ModelApi, on_delete=models.CASCADE,
verbose_name='MODEL API',
related_name='modelapiconfig')
api_config = models.TextField(default={})
def __str__(self):
return self.model_auth.model_id.model_name + str("'s ") \
+ self.model_api.api_endpoint_name + str(" endpoint")
class Meta:
unique_together = ('model_auth', 'model_api',)
db_table = "connector_model_api_config"
我要为该sql查询创建orm:
SELECT
connector_model.model_name,
connector_model_authentication.retrieval_id,
connector_model_authentication.model_config_data,
connector_model_api.api_endpoint_name,
connector_model_api_config.api_config
FROM connector_model
JOIN
connector_model_authentication ON (connector_model.id = connector_model_authentication.model_id_id)
LEFT OUTER JOIN
connector_model_api ON (connector_model.id = connector_model_api.model_id_id)
LEFT OUTER JOIN
connector_model_api_config ON (
connector_model_api.id = connector_model_api_config.model_api_id
and connector_model_authentication.id = connector_model_api_config.model_auth_id)
WHERE (connector_model_authentication.retrieval_id = 'XXYY'
AND connector_model_authentication.is_active = True);
在connector_model_api_config的左外部连接中,我在ON()子句中具有两个条件,那么如何在django orm查询中添加两个条件?
如果有人有解决方案,请帮助我。