Issue
I have a dynamic advanced search interface implemented in Django and javascript where the user selects:
- a field,
- a comparator (using a field lookup such as "iexact", "startswith", "gt", "lte", etc.), and
- a search term for any number of fields in the database
Currently, for the 2 duration fields we have (age and "sample collection time (since infusion)"), the user is required to enter their search term in a format compatible with the timedelta used for django's database query, e.g. d-hh:mm:ss
, foir the search to work properly.
What we would like to do is accept search terms in the units in which the data is entered in the database (age in weeks and time collected in minutes). I could of course write one-off code to accomplish this, but I want this advanced search module I've written to be a generic implementation, so we can apply it to other projects without changing any code...
So I was looking at the django doc's field lookups, which doesn't appear to have lookups for duration fields, but it links to a doc that gives advice on writing custom field lookups.
There are definitely a few ways I can think of to do this, but the path of least resistance would be to fit into the current paradigm by using duration-field specific field lookups to create a lookup for each case. So for example:
- gtmins = greater than this number of minutes
- ltmins = less than this number of minutes
- eqmins = equal to this number of minutes
- gtweeks = greater than this number of weeks
- ltweeks = less than this number of weeks
- eqweeks = equal to this number of weeks
- etc...
Those would be used in the following manner:
Animal.objects.filter(age__gtweeks=12)
...which would return all animals older than 12 weeks old.
The thing is that this feels like re-inventing the wheel. It's hard for me to believe that these field lookup features don't already exist. Am I missing something?
Another question that is a bit more involved would be, the builtin field lookups have a ways to drill down into a DateField in the following manner:
For a DateField, you can specify the lookup using units like week, where you can do something like:
Entry.objects.filter(pub_date__week__gte=32)
where it gets entry objects whose publication week (out of 52 weeks in the year) is greater than week 32.
Does there exist a similar unit-specification for DurationFields? E.g. Could I do:
Animal.objects.filter(age__weeks__gt=12)
?
Solution
You can use Django's Extract
function to return the Integer value of the particular part of a duration.
So for your example, I would probably use an annotate to extract the attribute and use that result in a filter:
Animal.objects.annotate(age_week=Extract(F('age'), 'week')).filter(age_week__gt=12)
Answered By - Bobort
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.