Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django admin select ordering different than default model ordering

I have a model (Node) which is ordered by date in the admin, so latest nodes are shown first. This is fine.

The same model (Node) is referenced by another model (Device). When editing a device there is a list of nodes (in an HTML select) which is also ordered by date. I would like this select to be ordered by name and not by date.

Is it possible to have two different ordering methods, one for the list of objects and one for the select box?

Thanks.

like image 877
nemesisdesign Avatar asked Jan 18 '12 23:01

nemesisdesign


People also ask

What is default ordering Django?

To sort QuerySets, Django uses the order_by() method: Descending Order. By default, the result is sorted ascending (the lowest value first), to change the direction to descending (the highest value first), use the minus sign (NOT), - in front of the field name: Multiple Order Bys.

What is the purpose of __ Str__ method in Django?

str function in a django model returns a string that is exactly rendered as the display name of instances for that model. # Create your models here. This will display the objects as something always in the admin interface.


2 Answers

The easiest thing would be to override the formfield_for_foreignkey method in the ModelAdmin for Device, something like

def formfield_for_foreignkey(self, db_field, request, **kwargs):
    if db_field.name == 'node':
        kwargs['queryset'] = Node.objects.order_by('name')
    return super(DeviceAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

(I'm assuming a fair amount here. Hopefully it's clear!)

Similarly there's formfield_for_manytomany.

like image 93
Ismail Badawi Avatar answered Oct 22 '22 12:10

Ismail Badawi


Have you tried something like:

class Node
        name = ...
        date = ...
        fields ....

        class Meta:
            order_with_respect_to='Device'
            ordering = ('Device', 'name')
like image 26
Priyeshj Avatar answered Oct 22 '22 10:10

Priyeshj