Nikunj Aggarwal
Nikunj Aggarwal

Reputation: 406

Django ORM simple Join

I want to perform simple join operation like this.

raw SQL : select * from risks r join sku_details s on r.sku_id = s.sku_id;

model Details:

class SkuDetails(models.Model):
    sku_id = models.DecimalField(primary_key=True, max_digits=65535, decimal_places=65535)
    sku_desc = models.TextField(blank=True, null=True)
    category = models.TextField(blank=True, null=True)



class Risks(models.Model):
    risk_id = models.DecimalField(primary_key=True, max_digits=65535, decimal_places=65535)
    risk_group_short_desc = models.TextField(blank=True, null=True)
    risk_group_desc = models.TextField(blank=True, null=True)
    var = models.DecimalField(max_digits=65535, decimal_places=65535, blank=True, null=True)
    sku = models.ForeignKey(SkuDetails, models.DO_NOTHING, blank=True, null=True)

After joining I want all the column of both the table in flat structure through Django ORM... In raw SQL I will get all the column ... But not getting from ORM

Please Help !!!

Upvotes: 1

Views: 87

Answers (2)

Shakil
Shakil

Reputation: 4630

You can try this withselect_related. Relevant helping material As both model with foreign-key relation.

Upvotes: 0

Endre Both
Endre Both

Reputation: 5730

Getting all values in a list of dictionaries is quite easy with values():

Risks.objects.values(
    'risk_id',
    'risk_group_short_desc`,
    # ... fields you need from Risks
    'sku__sku_id',
    # ... fields you need from SkuDetails
)

You can check out values_list() as well.

Upvotes: 1

Related Questions