Ranged headache

#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)
    ...

      

(Obviously the code doesn't work, I'm just using it to help illustrate my problem.)

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

So, if the promotion starts on 01.01.09 and ends on 30/01/09, and a person from 01/12/08 to 01/02/09, it will still return the result. Also if they are searching within a date range eg. 02/01/09 - 03/01/09 they will get the same result.

Is there any magical django way to achieve this without looping over each day?

+2


source to share


1 answer


You have four dates: start_search

, end_search

, start_promo

and end_promo

. Are you 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)

      

+1


source







All Articles