Custom Sorting on Custom Field in Django
- by RotaJota
In my app, I have defined a custom field to represent a physical quantity using the quantities package.
class AmountField(models.CharField):
def __init__(self, *args, **kwargs):
...
def to_python(self, value):
create_quantities_value(value)
Essentially the way it works is it extends CharField to store the value as a string in the database
"12 min"
and represents it as a quantities object when using the field in a model
array(12) * min
Then in a model it is used as such:
class MyModel(models.Model):
group = models.CharField()
amount = AmountField()
class Meta:
ordering = ['group', 'amount']
My issue is that these fields do not seem to sort by the quantity, but instead by the string.
So if I have some objects that contain something like
{"group":"A", "amount":"12 min"}
{"group":"A", "amount":"20 min"}
{"group":"A", "amount":"2 min"}
{"group":"B", "amount":"20 min"}
{"group":"B", "amount":"1 hr"}
they end up sorted something like this:
>>> MyModel.objects.all()
[{A, 12 min}, {A, 2 min}, {A, 20 min}, {B, 1 hr}, {B, 20 min}]
essentially alphabetical order.
Can I give my custom AmountField a comparison function so that it will compare by the python value instead of the DB value?