On Wed, Jul 6, 2011 at 12:36 AM, Venkatraman S <venka...@gmail.com> wrote:

> I tried asking around in IRC, and stumbled on a few possible solutions,
> would be great if someone shed some more light:
>
> I have the following models:
>
> class Organization(models.Model):
>   name                = models.CharField(max_length=100, blank=False)
>
> class Employees(models.Model):
>   org                 = models.ForeignKey(Organization,
> related_name='employees')
>   user                = models.ForeignKey(User)
>   name                = models.CharField(max_length=100, blank=False)
>
> class Item(models.Model):
>   name                = models.CharField(max_length=100, blank=False)
>   created_by          =
> models.ForeignKey(User,related_name='created_by_whom')
>
> Problem : I need to get all Items from the Organization to which current
> User belongs to.
> So basically, get all employees from the Org that the current User belongs
> to, and then get all items created by these employees. (So, this query
> should also include the current User).
>
> Say there are 3 Users in an org : A, B and C with each creating 3,4,5 items
> respectively, and 'A' is the current user; then i need a query which returns
> all these items(i.e, 12 items) when i supply A..
>


This is the equivalent raw sql:
select count(1)
from myapp_items a
where a.created_by_id in
(
select e.user_id
from myapp_employees e, myapp_organization o
where e.org_id = o.id
and o.id = (select o2.id from myapp_organization o2, myapp_employees e2
where e2.org_id = o2.id and e2.user_id=<<current_user_id>>)
)

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to