Reputation: 8529
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.
Upvotes: 8
Views: 1363
Reputation: 798
You can create custom form for DeviceAdmin and set queryset parameter for 'Node' field.
# in models.py we have Device model with Node field
class Device(models.Model):
node = models.ForeignKey(Node)
...
# in admin.py we have DeviceAdmin with custom form
class DeviceAdminForm(forms.ModelForm):
node = forms.ModelChoiceField(queryset=Node.objects.order_by('name'), label='Node')
class Meta:
model = Device
class DeviceAdmin(admin.ModelAdmin):
form = DeviceAdminForm
Upvotes: 0
Reputation: 1345
Have you tried something like:
class Node
name = ...
date = ...
fields ....
class Meta:
order_with_respect_to='Device'
ordering = ('Device', 'name')
Upvotes: 2
Reputation: 37187
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
.
Upvotes: 6