Shale
Shale

Reputation: 417

How can i change this query to ORM? (JOIN without foreign key and order by second table)

Hi i have two models like this,

class Sample(models.Model):
    name = models.CharField(max_length=256)  ##
    processid = models.IntegerField(default=0)  # 


class Process(models.Model):
    sample = models.ForeignKey(Sample, blank=False, null=True, on_delete=models.SET_NULL, related_name="process_set")
    endstat = models.CharField(max_length=5, choices=ENDSTATChoice, default='0')

and I want to join Sample and Process model. Because Sample is related to process and I want to get process information with sample .

SELECT sample.id, sample.name, process.id,process.endstat
FROM sample 
INNER JOIN process 
ON sample.processid = process.id 
ORDER BY process.endstat;

How can i do with ORM like this SQL?

Upvotes: 1

Views: 86

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476750

Since you want the data of the Process. It makes more sense to work with:

qs = Process.objects.filter(
    sample__isnull=False
).select_related('sample').order_by('endstat')

This will also fetch the related data for the related Sample, you thus can process this by accessing the fields of the .sample attribute:

for process in qs:
    print(process.sample.name)

Upvotes: 1

Related Questions