Thursday, December 1, 2011

select_related, need reverse foreighn key help

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__

 

No comments:

Post a Comment