2

I am trying to find a way to display a list of database objects in an order based on their status variable. The application is an order tracking app. Each order has a status: 'idle', 'awaiting delivery', 'ready for pickup', etc. I'm wanting to display the list of orders, sorted by their status. I already have a filter that is working, but I'm wondering if there is a way to sort the entire list of orders such that 'idle' orders are on top, followed by 'awaiting delivery' orders, and so on. Obviously, I can't just add status to ordering in the admin.py file, because that sorts statuses alphabetically.

Does anybody know a simple way to fix this issue? I'm sure I'm just over-thinking this whole thing..

Kevin Brown-Silva
  • 40,873
  • 40
  • 203
  • 237
nblakey
  • 97
  • 1
  • 8

2 Answers2

1

All I ended up doing was adding an alpha character to each status name. Since I already had a nice, neat verbose name for each status, I didn't think it affected readability too much. I can't say it's the best solution in the world, but I do believe it is the most simple.

   STATUS_OF_ORDER = (
     ('A_IDLE', 'Not yet ordered'),
     ('B_SHIP', 'Awaiting delivery'),
     ('C_PICK', 'Ready for pickup'),
     ('E_UNAV', 'Unavailable for order'),
     ('D_BACK', 'Backordered - awaiting delivery'),
     ('F_CANC', 'Canceled by customer'),
     ('G_ARCH', 'Fulfilled'),
   )
   status = models.CharField(max_length=6, choices=STATUS_OF_ORDER,
                             default='A_IDLE', editable=False)
nblakey
  • 97
  • 1
  • 8
0

If you want to sort in SQL there are two ways to achieve this.

create a model that links your status with numeric value

class status (Model.model):
    status = Model.CharField()
    sort_order = Model.IntegerField()

you can join this table with your order table and order by sort_order

If this seems not practical to you consider a custom query that does the ordering for you. You can attach this to your orm method with the .extra method. See more information about it in the django documentation

Order By Case
            When status_order Like 'idle Then 1
            When status_order Like 'awaiting delivery' Then 2
            When status_order Like 'ready for pickup' Then 3
            Else 99
            End Asc
Dr.Elch
  • 2,105
  • 2
  • 17
  • 23
  • I had thought about using an index like you mention as your first point. However, I didn't want to add anything to my database unless absolutely necessary. I also didn't really follow the second method you mentioned, as I'm still pretty new to Python/Django. – nblakey Apr 26 '14 at 02:11
  • Well just try it. It won't hurt ;-) – Dr.Elch May 08 '14 at 10:13