Reputation: 1282
I have a model
class Ticket(db.Document):
created = db.DateTimeField(default=datetime.utcnow)
ticket_number = db.StringField(unique=True)
I have ticket_number with integer values but stored as a string field. I want to query the ticket with the highest ticket number. What I have tried is
Ticket.objects.order_by('-ticket_number').first().ticket_number
But it returns 9
where it should be 20
.
The issue is the queryset gets sorted by string methods.
Is there any way to sort it numerically?
Or does mongo has some query functions like Cast
?
Upvotes: 0
Views: 92
Reputation: 1282
I got a solution that works for me.
Adding numericOrdering
to the query as collation resolves the issue.
The final query will look like
Ticket.objects.order_by("-ticket_number")
.collation({"locale": "en_US", "numericOrdering": True})
.first()
Upvotes: 1