Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Date Aggregate Function

I want to sort my Store models by their opening times. Store models contains is_open function which controls Store's opening time ranges and produces a boolean if it's open or not. The problem is I don't want to sort my queryset manually because of efficiency problem. I thought if I write a custom annotate function then I can filter the query more efficiently.

So I googled and found that I can extend Django's aggregate class. From what I understood, I have to use pre-defined sql functions like MAX, AVG etc. The thing is I want to check that today's date is in a given list of time intervals. So anyone can help me that which sql name should I use ?

Edit

I'd like to put the code here but it's really a spaghetti one. One pages long code only generates time intervals and checks the suitable one.

I want to avoid :

alg= lambda r: (not (s.is_open() and s.reachable))
sorted(stores,key=alg)

and replace with :

Store.objects.annotate(is_open = CheckOpen(datetime.today())).order_by('is_open')

But I'm totally lost at how to write CheckOpen...

like image 549
iva123 Avatar asked Dec 06 '25 20:12

iva123


1 Answers

have a look at the docs for extra

like image 132
second Avatar answered Dec 09 '25 14:12

second



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!