I have Django objects set up like:
class Example(models.Model):
count = models.CharField(default="0")
So if I have some objects ex1
, ex2
, ex3
, ex4
that have count of -1, 0, 5, -6 respectively. I want to be able to query the objects and sort them into the order [0, 5, -6, -1]
where any zeros come first, then positives, then negatives while also going in ascending order for each section. I was thinking about using something like Example.objects.order_by('count')
but did not find a way to do that with a custom function like this.
The other route I was looking at was something like below:
objs = Example.objects.all()
sorted_objs = sorted(objs, key = lambda o: int(o.count))
Is there a way to use the sorted method to sort the zeros first? I was unable to find one.
The final way I am using is:
objs = Example.objects.all()
zero_objs = []
positive_objs = []
negative_objs = []
for obj in objs:
if obj.count == 0:
zero_objs.append(obj)
elif obj.count < 0:
negative_objs.append(obj)
else:
postitive_objs.append(obj)
sorted_objs = zero_objs + sorted(postitive_objs) + sorted(negative_objs)
This works but seems like it's not the best way to do this, so any ideas would be great. As a side note, I am aware the count attribute would be better stored as an integer field, but I would like to accomplish this while keeping it a char field.