logoalt Hacker News

echoangleyesterday at 10:51 AM2 repliesview on HN

> I can't quite picture how operator overloading would look like, could you give an example?

Instead of this:

self.filter(end__gt=self._midnight(today))

You could write a "Field" class that implements __getattr__ and __gt__ so you could do

self.filter(Field.end > self._midnight(today))

The "Field.end > self._midnight(today)" would evaluate to an object that would just store "my field name is end and my value needs to be larger than xyz".

filter() can then look into its argument list and construct the filter criteria from the passed Field objects instead of the key value pairs as it does now.


Replies

mmclaryesterday at 10:47 PM

SQLalchemy does that. One advantage of the Django syntax is that it can be (pretty much) directly dropped into a query string on any admin page or DRF query and filter the results. E.g. the admin page for all the events after noon today:

  admin/event/?end__gt=2026-07-26T12:00:00
Being able to do ad-hoc queries using the same paradigm your app queries are written in, and then pass urls around with those queries included (e.g., quick one-off reports or answers to client questions) is so helpful.
pbalauyesterday at 11:12 AM

if self._midnight(today) returns a datetime object, than:

   self.filter(end__gt=self._midnight(today))
will evaluate to:

   self.filter(end__gt=<some_datetime_object>)

While

    self.filter(Field.end > self._midnight(today))
will evaluate to:

   self.filter(<True/False>)
show 3 replies