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.
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.
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.
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
.
Have you tried something like:
class Node
name = ...
date = ...
fields ....
class Meta:
order_with_respect_to='Device'
ordering = ('Device', 'name')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With