简体   繁体   English

在Django中联接多个表

[英]Joining Multiple Tables in Django

I have looked through around and there doesn't seem to be anything that has exactly answered what I am looking for, using the following model I want to join all the tables: 我浏览了一下,似乎没有什么可以完全满足我所寻找的东西,使用下面的模型,我想连接所有表:

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)

This is a very basic sort of structure I have going on, I want to join all the tables based on there foreign key link the A. I have looked at select_related but it seems like that is the reverse direction of what I want to do because it links an object to what it references and I want to join based on what references it. 这是我正在进行的一种非常基本的结构,我想基于那里的外键链接A来连接所有表。我已经看过select_related了,但这似乎是我想要做的事情的反向它将对象链接到它所引用的对象,我想根据引用的对象来加入。

Basically I want to join the tables like this MySQL query: 基本上我想像这样的MySQL查询联接表:
SELECT * FROM A, B, C, D WHERE A.id = B.aID AND A.id = C.aID AND A.id = D.aID;

You can use a custom join for your purpose: 您可以根据需要使用自定义联接

# 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)

Wash, rinse, repeat for every pair of tables till you're happy. 清洗,漂洗,对每对桌子重复,直到您感到满意为止。 If this is too involved, you can always use custom SQL . 如果涉及的过多,则始终可以使用自定义SQL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM