开发者

Making a fairly complex Django model method sortable in admin?

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!


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜