Question

During dehydration I create a custom value:

def dehydrate(self, bundle):
    bundle.data['custom_field'] = ["add lots of stuff and return an int"]
    return bundle

that I would like to filter on.

/?format=json&custom_field__gt=0...

however I get an error that the "[custom_field] field has no 'attribute' for searching with."

Maybe I'm misunderstanding custom filters, but in both build_filters and apply_filters I can't seem to get access to my custom field to filter on it. On the examples I've seen, it seems like I'd have to redo all the work done in dehydrate in build_filters, e.g.

for all the items:
    item['custom_field'] = ["add lots of stuff and return an int"]
    filter on item and add to pk_list 

orm_filters["pk__in"] = [i.pk for i in pk_list]

which seems wrong, as I'm doing the work twice. What am I missing?

Was it helpful?

Solution

The problem is that dehydration is "per object" by design, while filters are per object_list. That's why you will have to filter it manually and redo work in dehydration.

You can imagine it like this:

# Whole table
[obj, obj1, obj2, obj3, obj4, obj5, obj5]

# filter operations
[...]

# After filtering
[obj1, obj3, obj6]    

# Returning
[dehydrate(obj), dehydrate(obj3), dehydrate(obj5)] 

In addition you can imagine if you fetch by filtering and you get let say 100 objects. It would be quite inefficient to trigger dehydrate on whole table for instance 100000 records.

And maybe creating new column in model could be candidate solution if you plan to use a lot of filters, ordering etc. I guess its kind of statistic information in this field so if not new column then maybe django aggregation could ease your pain a little.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top