[BangPypers] Joins with Django

Puneet Aggarwal look4puneet at gmail.com
Thu May 7 07:37:12 CEST 2009


On Wed, May 6, 2009 at 7:39 PM, Baishampayan Ghose <b.ghose at gmail.com>wrote:

> > I am trying to learn django and write a small application. I am facing
> issue
> > in executing a join with django.
> > I am able to find a work around by executing a raw SQL query using
> cursor.
> > But that have problem that I need to access fields using
> > "object.0' or 'object.1'  which is too verbose and error prone.
> >
> > Is there better way of doing the same thing or executing joins using
> Django
> > models.
> >
> > here is my table structure
> >
> > table 1 : Company
> > id = IntField
> > name = CharField
> >
> > table 2 : Schmes
> > id = Int field
> > Name = CharFiled
> > comp_id = ForeignKey (company)
> >
> > table 3 : Price
> >
> > scheme_id = ForeignKey(Schemes)
> > price          = CharField()
> > Date          = DateTimeField()
> >
> > I want to execute a query on the price table where I can select the price
> of
> > all the schemes for the specified company.
> >
> > something like this if I write SQL :
> >
> > select price from Price, Schemes, Company where Price.scheme_id =
> Scheme.id
> > and Scheme.comp_id = Company.id and Company.id = 1.
>
> Puneet,
>
> Try something like this:
>
> company = Company.objects.get(name="foocorp")
> prices = Price.objects.filter(scheme_id__comp_id=company)
>
> You can use __ (double underscores) to span relationships.
>
> The Docs have more:
>
> http://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships
>
> Regards,
> BG
>
> --
> Baishampayan Ghose
> b.ghose at gmail.com
> _______________________________________________
> BangPypers mailing list
> BangPypers at python.org
> http://mail.python.org/mailman/listinfo/bangpypers
>

Thanks Praveen and Baishampayan for the response. I will try out the
suggestions.


Thanks,
Puneet
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/bangpypers/attachments/20090507/c5d4735b/attachment.htm>


More information about the BangPypers mailing list