Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Admin : ordering items in a selection list [closed]

Tags:

django

I have 2 models : Product and Category. When I create a new product in my admin interface, I have to select a Category in a list. But I'd like to order these Categories by name this my list. After searching for it on the internet, i didnt find the solution yet.

Is there a way to do that ?

like image 407
PinkPR Avatar asked Mar 22 '23 22:03

PinkPR


1 Answers

You could set a default ordering in the meta class of your model definition:

class Category(models.Model):
    name = models.CharField(...)
    [ other fields ... ]
    class Meta:
        ordering = ['name']

By that, any query on Category will be ordered by default on the name field. This may be a disadvantage if unnecessary ordering affects the performance in other views/locations of your app. Apart from that, you may also modify the ordering inside your admins.py. The basics for that look like this. You'll need to adapt this snippet to your specific app:

from django import forms
from django.contrib import admin
from my_project.my_app.models import Category, Product

class ProductAdmin(admin.ModelAdmin):
    def formfield_for_dbfield(self, db_field, **kwargs):
        field = super(ProductAdmin, self).formfield_for_dbfield(db_field, **kwargs)
        if db_field.name == 'category':
            field.queryset = Category.objects.all().order_by('name')
        return field
    list_display = ('...', '...', ...)
    [ other admin definitions ... ]
admin.site.register(Product, ProductAdmin)

The accepted answer on this SO question adds another solution: Django Admin: Ordering of ForeignKey and ManyToManyField relations referencing User

like image 123
Simon Steinberger Avatar answered Apr 06 '23 01:04

Simon Steinberger