Re: Quick Query Question

2007-05-15 Thread Jeremy Dunck

On 5/15/07, Collin Anderson <[EMAIL PROTECTED]> wrote:
> class Laptop(models.Model):
> def laptops_out_on(date):
> 'get a list of laptops out on a given day'
> result = Laptop.objects.none()
> for x in Rental.objects.filter(checkout__lte=date,
> checkin__gte=date):
> result = result | x.laptops.all()
> return result
> laptops_out_on = staticmethod(laptops_out_on)

Why not get the list of active rentals (1 query) then get the list of
laptops associated with those rentals?

Also, make it a manager method rather than a static method.

class LaptopManager(models.Manager):
   def checked_out(self, date=None):
  if date is None:
 import datetime
 date = datetime.date.today()
  active_rental_ids = [rental['id'] for rental in
Rental.objects.filter(checkout__gte=date,
checkin_lte=date).values('id')]
  qs = super(LaptopManager, self).get_query_set().
  return qs.filter(rental__id__in=active_rental_ids)

class Laptops(models.Model):
  objects = LaptopManager()


#get all checked out laptops today:
Laptops.objects.checked_out()

...Code not tested since I can't sandbox a project and DB quickly just now.

More:
http://www.djangoproject.com/documentation/db-api/#lookups-that-span-relationships

--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Quick Query Question

2007-05-15 Thread Collin Anderson

I am working with a laptop rental program, and I was wondering if
there is a better way to do this lookup. This works fine, but it seems
like it could be better.

from django.db import models

class Laptop(models.Model):
def laptops_out_on(date):
'get a list of laptops out on a given day'
result = Laptop.objects.none()
for x in Rental.objects.filter(checkout__lte=date,
checkin__gte=date):
result = result | x.laptops.all()
return result
laptops_out_on = staticmethod(laptops_out_on)

class Rental(models.Model):
checkout = models.DateField(blank=True)
checkin = models.DateField(blank=True)
laptops = models.ManyToManyField(Laptop, blank=True)

Thanks,
Collin


--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---