简体   繁体   中英

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.

Basically I want to join the tables like this MySQL query:
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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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