Skip to content Skip to sidebar Skip to footer

Django - Join Two Table Without Foreign Key

I have two tables and want to join them.. but I can't do that without rawQueryset and raw SQL. how can i join two models without foreign key? The columns for JOIN is not unique so

Solution 1:

You can try this:

Firstly, construct a SQL query as desired

sql_query = "SELECT * FROM genome AS A JOIN metadata AS B ON A.query_id = B.sample_id"

User that SQL query in django DB connection like following:

from django.db import connection

defmy_custom_sql(self):
    cursor = connection.cursor()    
    cursor.execute(sql_query)
    row = cursor.fetchall()
    return row

Or you can try to execute raw() as following

Genome.objects.raw(sql_query) # in some cases it may not work

Solution 2:

You can try this:

sample_ids = Metadata.objects.values('sample_id')
Genome.objects.filter(query_id__in=sample_ids)

Post a Comment for "Django - Join Two Table Without Foreign Key"