在Django中加入多个表

时间:2014-02-08 17:43:01

标签: python mysql database django

我已经浏览了周围,似乎没有任何东西能够正确回答我想要的东西,使用以下模型我想加入所有表格:

class A(models.Model):
    name = models.CharField(max_length=60)

class B(models.Model):
    a = models.ForeignField(A)

class C(models.Model):
    a = models.ForeignField(A)

class D(models.Model):
    a = models.ForeignField(A)

这是我正在进行的一种非常基本的结构,我想基于那里的外键链接加入所有表A.我看了select_related但看起来这是我想要的反方向这样做是因为它将一个对象链接到它引用的对象,并且我想根据它引用它来加入。

基本上我想加入像这样的MySQL查询表:
SELECT * FROM A, B, C, D WHERE A.id = B.aID AND A.id = C.aID AND A.id = D.aID;

1 个答案:

答案 0 :(得分:0)

您可以将a custom join用于您的目的:

# assume our models.py contains the following
class Contact(models.Model):
    name = models.CharField(max_length=255)
    phones = models.ManyToManyField('Phone')
    addresses = models.ManyToManyField('Address')

class Phone(models.Model):
    number = models.CharField(max_length=16)

# join as follows
contacts = Contact.objects.extra(
    select={'phone': 'crm_phone.number'}
).order_by('name')

# setup intial FROM clause
# OR contacts.query.get_initial_alias()
contacts.query.join((None, 'crm_contact', None, None))

# join to crm_contact_phones
connection = (
    'crm_contact',
    'crm_contact_phones',
    'id',
    'contact_id',
)
contacts.query.join(connection, promote=True)

# join to crm_phone
connection = (
    'crm_contact_phones',
    'crm_phone',
    'phone_id',
    'id',
)
contacts.query.join(connection, promote=True)

每一张桌子都要洗净,冲洗,重复,直到你开心。如果过于复杂,您可以随时使用custom SQL