Making a fairly complex Django model method sortab

2019-05-05 06:58发布

I have a reasonably complex custom Django model method. It's visible in the admin interface, and I would now like to make it sortable in the admin interface too.

I've added admin_order_field as recommended in this previous question, but I don't fully understand what else I need to do.

class Book(models.Model):
    id = models.IntegerField(primary_key=True)
    title = models.CharField(max_length=200)
    library_id = models.CharField(max_length=200, unique=True)
    def current_owner(self):
        latest_transaction = Transaction.objects.filter(book=self)[:1]
        if latest_transaction:
            if latest_transaction[0].transaction_type==0:
                return latest_transaction[0].user.windows_id
        return None
    current_owner.admin_order_field = 'current_owner'

Currently, when I click on the current_owner field in the admin interface, Django gives me

FieldError at /admin/books/book/
Cannot resolve keyword 'current_owner' into field

Do I need to make a BookManager too? If so, what code should I use? This isn't a simple Count like the example in the previous question, so help would be appreciated :)

Thanks!

2条回答
Luminary・发光体
2楼-- · 2019-05-05 07:18

You can't do this. admin_order_field has to be a field, not a method - it's meant for when you have a method that returns a custom representation of an underlying field, not when you do dynamic calculations to provide the value. Django's admin uses the ORM for sorting, and that can't sort on custom methods.

查看更多
Bombasti
3楼-- · 2019-05-05 07:34

The Django admin won't order models by the result of a method or any other property that isn't a model field (i.e. a database column). The ordering must be done in the database query, to keep things simple and efficient.

The purpose of admin_order_field is to equate the ordering of a non-field property to the ordering of something that is a field.

For example, a valid values current_owner.admin_order_field could be id, title or library_id. Obviously none of these makes sense for your purpose.

One solution would be to denormalise and always store current_owner as a model field on Book; this could be done automatically using a signal.

查看更多
登录 后发表回答