【发布时间】:2013-12-16 12:10:10
【问题描述】:
我正在使用已使用以下模型映射到 Django ORM 的外部 MySQL 数据库:
class SchemaCategory(models.Model):
schema_id = models.IntegerField(primary_key=True)
language_id = models.IntegerField(primary_key = True)
category = models.CharField(max_length = 255L,blank = True)
unique_together = (('schema_id','language_id',),)
class Equipment(models.Model):
vehicle_id = models.BigIntegerField(primary_key = True)
schema_id = models.IntegerField(primary_key = True)
option_id = models.IntegerField(primary_key = True)
record_id = models.IntegerField(primary_key = True)
location = models.CharField(max_length=50L, blank=True)
data_value = models.CharField(max_length=255L,primary_key = True)
condition = models.TextField(blank=True)
unique_together = (('vehicle_id','schema_id','option_id','data_value','record_id'))
class Meta:
db_table = 'equipment'
class OptionList(models.Model):
vehicle_id = models.BigIntegerField(primary_key = True)
option_id = models.IntegerField(primary_key = True)
option_type = models.CharField(max_length=10L)
option_code = models.CharField(max_length=255L, blank=True)
manuf_name = models.CharField(max_length=255L)
#...
unique_together = (('vehicle_id','option_id'),)
class Meta:
db_table = 'option_list'
现在,我想从 OptionList 中为给定的 vehicle_id 加载所有条目,并且对于每个选项,加入适用于它的 SchemaCategories。 OptionList 和 SchemaCategory 通过 Equipment 表关联(vehicle_id 和 option_id 产生 schema_id,可以用来获取所有类别)。现在我正在使用如下所示的 MySQL 查询:
select A.option_type,
A.option_code,
A.manuf_name,
A.option_id,
group_concat(distinct C.category) as category
from option_list A
left join equipment B
on
A.vehicle_id = B.vehicle_id
and
A.option_id = B.option_id
left join schema_categories C
on
C.language_id = 3
and
C.schema_id = B.schema_id
where
A.vehicle_id=?
group by
A.option_id
order by
A.manuf_name asc
知道如何使用 Django ORM 实现这一点吗?我尝试通过 Equipment 表在 OptionList 和 SchemaCategory 之间使用 ManyToMany 关系,但我不确定如何使用 ORM 指定连接的 ON 条件。
【问题讨论】:
-
可以使用原始sql吗? docs.djangoproject.com/en/1.6/topics/db/sql
-
嗯,它很脏,但它可以解决问题。感谢您指出!
标签: python mysql sql django orm