views:

44

answers:

1
#model
class Promotion(models.Model):
    name = models.CharField(max_length=200)
    start_date = models.DateTimeField()
    end_date = models.DateTimeField()


#view
def promo_search(request):
    ...
    results = Promotion.objects.filter(start_date__gte=start_date).filter(end_date__lte=end_date)
    ...

(The code above obviously isn't going to work I'm just using it to help illustrate my problem.)

I want to show all active promotions between the start date and end date.

So if a promotion starts on 01/01/09 and ends 30/01/09 and a person searches from 01/12/08 to 01/02/09 it will still return a result. Also if they search from inside the date range e.g. 02/01/09 - 03/01/09 they would get the same result.

Is there some magical django way of achieving this without looping over each day?

+1  A: 

You have four dates to consider: start_search, end_search, start_promo and end_promo. You are looking for promotions where start_promo <= end_search and end_promo >= start_search:

results = Promotion.objects.\
            filter(start_date__lte=end_date).\
            filter(end_date__gte=start_date)
Ned Batchelder
Thanks, working now :)
Rob B