Reputation: 11
I have a model in django admin like below:
class NotificationMapping(models.Model):
counterId = models.ForeignKey(CounterDetails)
groupId = models.ForeignKey(CounterGroup)
class Meta:
unique_together = ('counterId', 'groupId',)
ModelAdmin:
class NotificationMappingAdmin(admin.ModelAdmin):
list_display = ('get_counterId', 'get_groupId',)
actions = None
# if display name is available for the counter display it
# if not display counterId
def get_counterId(self, obj):
if obj.counterId.displayName:
return obj.counterId.displayName
else:
return obj.counterId.counterId
get_counterId.admin_order_field = 'counterId' # Allows column order sorting
get_counterId.short_description = 'counter' # Renames column head
# show groupId on admin page for notification mapping
def get_groupId(self, obj):
return obj.groupId.groupId
get_groupId.admin_order_field = 'groupId' # Allows column order sorting
get_groupId.short_description = 'groupId' # Renames column head
I need to sort the values in the foreign key dropdown from where we add new entry.
Upvotes: 0
Views: 2440
Reputation: 1
You can override formfield_for_foreignkey() for sorting as shown below:
class NotificationMappingAdmin(admin.ModelAdmin):
list_display = ('get_counterId', 'get_groupId',)
actions = None
def formfield_for_foreignkey(self, db_field, request, **kwargs):
formfield = super().formfield_for_foreignkey(db_field, request, **kwargs)
if db_field.name == "get_counterId":
formfield.queryset = CounterDetails.objects.all().order_by('-id')
if db_field.name == "get_groupId":
formfield.queryset = CounterGroup.objects.all().order_by('-id')
return formfield
Upvotes: 0
Reputation: 1121
You can do this:
class NotificationMappingAdmin(admin.ModelAdmin):
list_display = ['get_counterId', 'get_groupId',]
ordering = ('id',)
def get_form(self, request, obj=None, **kwargs):
form = super(NotificationMappingAdmin, self).get_form(request, obj, **kwargs)
form.base_fields['get_counterId'].queryset = CounterDetails.objects.all().order_by('-id')
form.base_fields['get_groupId'].queryset = CounterGroup.objects.all().order_by('-id')
return form
Upvotes: 3