Skip to content

Instantly share code, notes, and snippets.

@okaram
Created September 11, 2012 21:33
Show Gist options
  • Save okaram/3702234 to your computer and use it in GitHub Desktop.
Save okaram/3702234 to your computer and use it in GitHub Desktop.
models for join django example
ph2=Phone.objects.create(person=p1,area_code='770',number='1234567');
Person.objects.filter(phone_set__area='770');
Person.objects.filter(phone_set__area='770').distinct();
class Person(models.Model):
name=models.CharField(max_length=20);
def __unicode__(self):
return self.name;
class Phone(models.Model):
person=models.ForeignKey(Person);
area_code=models.CharField(max_length=3);
number=models.CharField(max_length=7);
def __unicode__(self):
return "("+self.area_code+")"+self.number +" for " +self.person.name;
In [8]: Person.objects.filter(phone__area_code='770')
Out[8]: [<Person: Orlando>, <Person: Orlando>]
In [9]: Person.objects.filter(phone__area_code='770').distinct()
Out[9]: [<Person: Orlando>]
from joins.models import *;
p1=Person.objects.create(name='Orlando');
ph1=Phone.objects.create(person=p1,area_ code='770',number='1234567');
SELECT *
FROM Person
WHERE id in (
SELECT person_id
FROM Phone
WHERE area_code='770'
)
SELECT Person.*
FROM Person JOIN Phone ON (Person.id=Phone.person_id)
WHERE Phone.area_code='770'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment