Home How to perform Left Outer Join in Django ORM ?
Reply: 1

How to perform Left Outer Join in Django ORM ?

amulya349 Published in 2017-10-27 06:27:58Z

I have the following models:

class CandidateDetail(models.Model):
    full_name = models.CharField(max_length=128, null=True)
    email_id = models.CharField(max_length=64, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    modified_at = models.DateTimeField(auto_now=True)

class Retake(models.Model):
    id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True)
    candidate_detail = models.ForeignKey('CandidateDetail')
    is_expired = models.BooleanField(default=False)
    owner_detail = models.ForeignKey(User)
    created_at = models.DateTimeField(auto_now_add=True)
    modified_at = models.DateTimeField(auto_now=True)

I want to perform the following Left Outer Join Query:

SELECT s.*, r.* FROM app_candidatedetail s LEFT OUTER JOIN app_retake r ON (s.id = r.candidate_detail_id)

The DB is Postgresql.

I could do the query using

qset = CandidateDetail.objects.raw('SELECT s.*, r.* FROM app_candidatedetail s LEFT OUTER JOIN app_retake r ON (s.id = r.candidate_detail_id)')

The id field of CandidateDetail table is the default id of Django which is an IntegerField acting as primary key.

But, I want to use this in serializer to return the result as JSON, which I couldn't find out. Please help me with this issue on how to write ORM query for this as well as how to make a serializer for this query.


Mohideen ibn Mohammed
Mohideen ibn Mohammed Reply to 2017-10-27 06:58:43Z

since your requirement is JSON,

try this,

>>> emp = Resource.objects.filter(der_current_role="2D Supervisor").values()
>>> for i in emp:
...  i.update(Role.objects.filter(emp_id=i['emp_id']).first().__dict__)
>>> emp
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.303412 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO