简体   繁体   English

我可以更改在 Django Admin 中使用 @admin.display 装饰器的 readonly_fields 的显示顺序吗?

[英]Can I change the display order of readonly_fields that use the @admin.display decorator in Django Admin?

Ok, so here's my problem.好的,这就是我的问题。 I'll try not to go round the houses too much.我会尽量不绕房子太多。

I have a django model which I want to expose with an admin interface.我有一个 django 模型,我想用管理界面公开它。 It foreign keys to a user model.它是用户模型的外键。 Something like (note ordering of other fields):类似的东西(注意其他字段的顺序):

class SomeModel(models.Model):
   user = models.ForeignKey(...)
   other_field2 = models.IntegerField(...)
   other_field1 = models.IntegerField(...)
   other_field3 = models.IntegerField(...)
   ...

I also have an admin interface for this model which looks like this:我还有一个该模型的管理界面,如下所示:

class SomeModelAdmin(admin.ModelAdmin):

   @admin.display(description="User id")
   def get_user_id(self, obj):
      return obj.user.id

   list_display = (
      "get_user_id",
      "other_field1",
      "other_field2",
      "other_field3",
   )

   readonly_fields = (
      "get_user_id",
      "other_field1",
      "other_field2",
   )

As far as I can see from the docs I can only use the @admin.display decorator for list_display and read_only_fields .据我从文档中看到的,我只能将@admin.display装饰器用于list_displayread_only_fields But what if I want to change the order that the fields are displayed in?但是,如果我想更改字段的显示顺序怎么办? In the above code they'll default to the order defined in the model (read only User id comes first, followed by other_field2 and other_field1 then finally an editable other_field3).在上面的代码中,它们将默认为模型中定义的顺序(首先是只读用户 id,然后是 other_field2 和 other_field1,最后是可编辑的 other_field3)。

I was hoping I could do this by defining a fields tuple or overriding the get_fields method, but this won't work for fields that use @admin.display .我希望我可以通过定义fields元组或覆盖get_fields方法来做到这一点,但这不适用于使用@admin.display的字段。 Any ideas?有任何想法吗?

Ah I was being blind, this is in the docs https://docs.djangoproject.com/en/4.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.fields .啊我是盲人,这是在文档https://docs.djangoproject.com/en/4.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.fields中。 You do this by defining tuple of readonly_fields, including the admin.display methods and then using those readonly fields in the fields tuple.您可以通过定义 readonly_fields 的元组(包括 admin.display 方法)然后在字段元组中使用那些只读字段来完成此操作。 Eg:例如:

   readonly_fields = (
      "get_user_id",
      "other_field1",
      "other_field2",
   )

   fields = (
      "get_user_id",
      "other_field1",
      "other_field2",
      "other_field3",
   )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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