vba_user
vba_user

Reputation: 125

Django - ForeignKey - how to use it correctly?

I have following DB model:

class Table1( models.Model ):       
    sctg = models.CharField(max_length=100, verbose_name="Sctg")
    emailAddress = models.CharField(max_length=100, verbose_name="Email Address", default='')

    def __unicode__(self):
        return str( self.sctg )


class Table2( models.Model ):

    sctg = models.ForeignKey( Table1 )
    street = models.CharField(max_length=100, verbose_name="Street")
    zipCode = models.CharField(max_length=100, verbose_name="Zip Code")

    def __unicode__(self):
        return str( self.sctg )

and I would like to execute select query. This is what I did:

sctg = Table1.objects.get( sctg = self.sctg )
data = Table2.objects.get( sctg = sctg  )

and it works but now I am executing 2 queries. Is there a chance to do this in only one ? in raw SQL I'd do a JOIN query but no idea how to do this in Django models.

Upvotes: 1

Views: 39

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476493

You can use two consecutive underscores to look "through" a ForeignKey reference. So your query is equivalent to:

Table2.objects.get(sctg__sctg=self.sctg)

The non-boldface part thus looks through the ForeignKey, whereas the boldface part corresponds to the CharField column.

Note that

  1. it is possible that there is no such Table2 element, or multiple. In both cases this will result in an error. In case you want to retrieve all (possibly empty), you can use .filter(..) over .get(..);
  2. here self.sctg should be a string (or something string-like) since the sctg of Table1 is a CharField.

The above will result in some sort of query like:

SELECT t2.*
FROM table2 AS t2
INNER JOIN table1 AS t1 ON t2.sctg = t1.id
WHERE t1.sctg = 'mysctg'

where 'mysctg' is the value stored in you self.sctg.

Upvotes: 3

Related Questions