Thursday, December 1, 2011

Re: select_related, need reverse foreighn key help

On Thu, Dec 1, 2011 at 5:13 PM, Sells, Fred
<fred.sells@adventistcare.org> wrote:
> I've got a model structure like this
>
>
>
> class Order(models.Model):
>
>     id = models.CharField(max_length=10, primary_key=True)  # like
> OT-6212345
>
>     facility = models.ForeignKey(Facility)
>
>     therapy = models.CharField(max_length=2, blank=True)
>
>     . . .
>
>
>
> class Schedule(models.Model):
>
>     facility = models.ForeignKey(Facility)  #yes I  know this is redundant,
> but handy for debugging in sql.
>
>     order = models.ForeignKey(Order)
>
>     . . .
>
>
>
> I need to find a list of all orders at a facility that have not been
> scheduled; BUT I also need a specific set of values.  I can do it using the
> following, but since the result is a list rather than a queryset, I can no
> longer use the .values() method.  I could "brute force" it but I've gotta
> believe Django can do this and it's just my lack of experience.  My code is
>
>
>
>
>
> class Test(unittest.TestCase):
>
>
>
>     def testOrderFilters(self):
>
>         values = tuple('id resident_id therapy resident__lname
> resident__fname resident__room resident__payor'.split())
>
>         facility = models.Facility.objects.get(pk='xx')
>
>         queryset = models.Order.objects.filter(facility=facility)
>
>         queryset = queryset.filter(therapy='OT').select_related()
> #sometimes want all, othertimes just one type
>
>         unscheduled = [x for x in queryset if not x.schedule_set.all()]
>
>         for u in unscheduled: print u.schedule_set.all(), u.__dict__
>
>
>

(I don't know what mail client you are using, but it made gmail think
that every line is double space, and I cba to fix it)

Sounds like you want all the orders for a particular facility where
the number of schedules is 0?

> from django.db.models import Count
> Order.objects.filter(facility=facility).annotate(num_schedules=Count('schedule')).filter(num_schedules=0)

https://docs.djangoproject.com/en/1.3/topics/db/aggregation/#generating-aggregates-for-each-item-in-a-queryset

Cheers

Tom

--
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+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment