Search code examples
mysqldjangoorminner-join

Django : select all columns when innerjoin using extra without foreignkey


I have two tables and they do not have foreign key or relationship. However, I have to do join and get all columns from both tables. This is the query I've made.

query = Sms.objects \
        .extra(tables=['product'], where=['product.id=sms.sms_id'])

When I printed raw query, I could check it only gets tables from Sms model, not from product model. Is there any way to get columns from product model?


Solution

  • Sounds like you need some raw queries

    Obviously you will need to customize your SQL depending on what your needs are and how you want/need to access the data. But here's a very simple example:

    crsr = dbconnection.cursor()
    myresults = crsr.execute("SELECT A.*, B.* FROM A,B WHERE A.ID=B.ID")
    for myresult in myresults:
        print('{} {} {}'. format(myresult[0], myresult [1], myresult[2]))
    crsr.close()
    

    The django documentation on this subject is very good. This is a powerful feature of Django. But with great power...