Home > front end >  django ORM join statements
django ORM join statements

Time:03-17

I'm learning django queryset API and it's so overwhelming. I'm used to sql statement and I just want a basic join statement where 2 tables join together

How can i get this result in shell?

SELECT e.emp_lastname,e.emp_firstname,o.job_description
FROM hs_hr_employee e
INNER JOIN ohrm_job_title o ON e.job_title_code = o.id
WHERE e.work_station='101';

hs_hr_employee

from django.db import models

class HsHrEmployee(models.Model):
emp_number = models.AutoField(primary_key=True)
employee_id = models.CharField(max_length=50, blank=True, null=True)
emp_lastname = models.CharField(max_length=100)
emp_firstname = models.CharField(max_length=100)
job_title_code = models.ForeignKey('OhrmJobTitle', models.DO_NOTHING, 
db_column='job_title_code', blank=True, null=True)
work_station = models.ForeignKey('OhrmSubunit', models.DO_NOTHING, 
db_column='work_station', blank=True, null=True)

hs_hr_job_title

class OhrmJobTitle(models.Model):
job_title = models.CharField(max_length=100)
job_description = models.CharField(max_length=400, blank=True, 
null=True)

i added the models

CodePudding user response:

You can filter with:

qs = HsHrEmployee.objects.filter(
    work_station_id=101
).select_related('job_title_code')

For the HsHrEmployee model objects that arise from this queryset, you can then determine the job_title for example with:

for item in qs:
    print(item.job_title_code.job_title)
  • Related