Django:使用多个密钥通过中间表创建M2M关系

时间:2013-12-16 12:10:11

标签: python mysql sql django orm

我正在使用我使用以下模型映射到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条件。

1 个答案:

答案 0 :(得分:0)

看起来您正在寻找一种方法来为多对多关系添加额外数据。检查此answer。在其中,您还可以找到解释该主题的Django文档的链接。