Creating a pretty complicated Django model method, sorted in admin?

I have a rather complicated custom method of the Django model. This is visible in the admin interface, and now I would like to make it sortable in the admin interface.

I added admin_order_field as recommended in this previous question , but I don't quite 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 do BookManager? If so, what code should I use? This is not a simple graph, as an example in the previous question, so help will be appreciated :)

Thanks!

+4
source share
2 answers

The Django administrator will not order models based on the result of a method or any other property that is not a model field (i.e. a database column). The order must be executed in a database query so that everything is simple and efficient.

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

For example, valid current_owner.admin_order_field can be id , title or library_id . Obviously, none of them makes sense for your purpose.

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

+2
source

You cannot do this. admin_order_field should be a field, not a method - this meant when you have a method that returns a custom representation of the base field, and not when you perform dynamic calculations to provide the value. The Django administrator uses ORM to sort and cannot sort by user methods.

+1
source

Source: https://habr.com/ru/post/1334655/


All Articles