Note that there are some explanatory texts on larger screens.

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

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload