简体   繁体   中英

custom field ordering in django admin

I am facing strange issue with custom field in django admin, Here I am trying ordering the field using django model manager.

class PracticeManager(models.Manager):
    def get_query_set(self, ):
        qs = super(PracticeManager, self).get_query_set().all()
        # qs = sorted(qs, key=operator.attrgetter('id'))
        print qs
        return qs

class Practice(models.Model):
    """docstring for Practice"""
    name = models.CharField(max_length=20, verbose_name='Name')
    ip = models.IPAddressField(verbose_name="Ip Address")
    objects = PracticeManager()

    def number_of_orders(self):
        return u'%s' % self
    number_of_orders.admin_order_field = 'ip' 

admin.py:

class PracticeAdmin(admin.ModelAdmin):
      list_display = ('number_of_orders', 'name')

The above code works fine and prints the list of objects in the terminal and also django admin dashboard working perfectly,

[<Practice: 10.90.90.1>, <Practice: 10.90.90.13>, <Practice: 9.5.3.2>, <Practice: 10.90.90.11>]

But when I enable the below line,

qs = sorted(qs, key=operator.attrgetter('id'))

It throws strange error on the admin dashboard panel,

Database error
Something's wrong with your database installation. Make sure the appropriate database tables have been created, and make sure the database is readable by the appropriate user.

But the object list prints on the terminal. Why I am facing this problem ?

By using sorted , you're converting the queryset to a list. But get_query_set must return a queryset, hence the name: anything that operates on the values returned from that manager will be expecting a QS.

There's no good reason to do that sort in Python. You should add it to the ORM call:

qs = super(PracticeManager, self).get_query_set().order_by('id')

or even better, set the ordering attribute in the model's Meta class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM