Katsuya Obara
Katsuya Obara

Reputation: 963

How to write queryset across 3 tables in Django?

I want to write queryset across 3 tables. (models are shown as below)
As outcome, I want to get below information.
{"naming1":"lpd1","naming2":"lpd2",...}
Can anyone tell me how to write this query?

models.py

class zone(models.Model):
    zone=models.CharField(max_length=20)

    def __str__(self):
        return self.zone

class light(models.Model):
    zone=models.OneToOneField(zone, primary_key=True, on_delete=models.CASCADE)
    lpd=models.IntegerField() <=extract

class naming(models.Model):
    zone=models.ForeignKey(zone)
    naming=models.CharField(max_length=20) <=extract

Upvotes: 0

Views: 43

Answers (1)

Todor
Todor

Reputation: 16010

You are basically looking for namings with their related zone-lights.

Its simple as:

# NOTE: read PEP8
# Your model names should be in CapWords
namings = Naming.objects.select_related('zone__light')

for naming in namings:
    print (naming.naming, naming.zone.light.lpd)

Upvotes: 1

Related Questions