python - 如何在“字段”元组中包含外键字段以使其显示在 Django Admin 的详细视图页面上
问题描述
模型: 我有一个这样的模型
class TestModel1(models.Model):
bookingid = models.ForeignKey(paymenttable) // foreign key
name = models.CharField(max_length=100, null=False, db_index=True)
// I want this to be displayed in both the list view and detail view
@property
def custom_field(self):
return self.bookingid.username
管理员.py
class MyAdmin(ReadOnlyAdminFields,admin.ModelAdmin):
// this works and i get custom_field in list view
list_display = ('custom_field', 'name')
readonly = ('custom_field', 'name')
// this dosent work and gives error
fields = ('custom_field', 'name')
错误:未知字段 custom_field。检查 MyAdmin 类的字段/字段集/排除属性
解决方案
你有一个小错字。readonly
应该readonly_fields
一个小技巧,你可以在你的方法中添加一个带有short_description
属性的自定义标签custom_field
。你可以这样做...
# models.py
class TestModel1(models.Model):
bookingid = models.ForeignKey(paymenttable)
name = models.CharField(max_length=100, null=False, db_index=True)
@property
def custom_field(self):
return self.bookingid.username
custom_field.short_description = "User"
然后你可以像这样在管理类的字段列表中使用它......
# admin.py
class MyAdmin(ReadOnlyAdminFields,admin.ModelAdmin):
list_display = ('custom_field', 'name')
readonly_fields= ('custom_field', 'name')
fields = ('custom_field', 'name')
推荐阅读
- git - 如何仅将一个项目从 svn 存储库转换为 git?
- c# - 如何使用实体框架中的关系获取表
- c# - 这种嵌套的泛型方法怎么解决呢?
- javascript - 如何在递归中转换函数
- python - 为课堂外的scrapy设置开始网址
- angular - Angular Reactive Form - 从 HTML 手动更新 FormGroup
- excel - 如何使用 office-js 在任务窗格 [加载项] 中列出所有工作簿工作表?
- kibana - 从开发环境打开kibana主页失败
- swift - Swift:“'Any'类型的值没有下标”错误/ swift 5
- javascript - Webpack 构建不适用于爬虫