[英]How to access attributes of the 'User' model extended by another model referenced by a OnetoOneField in admin.py
In model.py, I have a class extending the User model在 model.py 中,我有一个 class 扩展用户 model
class Tutor(models.Model):
user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
In admin.py, I tried to access user.id with 'user_id', which works在 admin.py 中,我尝试使用“user_id”访问 user.id,这很有效
class TutorAdmin(admin.ModelAdmin):
list_display = ('user_id', 'contact_number')
However, when I try to access other attributes of 'user' such as username, email with this format但是,当我尝试使用这种格式访问“用户”的其他属性时,例如用户名 email
class TutorAdmin(admin.ModelAdmin):
list_display = ('user_id', 'user_username', 'contact_number')
What is the format to access attributes such as user.username or user.email?访问 user.username 或 user.email 等属性的格式是什么?
UPDATE更新
Solved it with解决了
class TutorAdmin(admin.ModelAdmin):
@admin.display(description='username')
def username(self):
u = self.user
if u is not None:
return u.username
@admin.display(description='email')
def email(self):
u = self.user
if u is not None:
return u.email
list_display = ('user_id', username, email, 'contact_number')
Thanks to the solution by Willem Van Onsem感谢Willem Van Onsem的解决方案
You can define methods and reference these in the list_display
:您可以定义方法并在
list_display
中引用它们:
class TutorAdmin(admin.ModelAdmin):
list_display = ('user_id', 'contact_number',
username)
@admin.display(description='username')
def
username(self, obj):
u = obj.user
if u is not None:
return u.username
You can however not edit the usernames, since the function defines how to access the data, not how to alter it.但是,您不能编辑用户名,因为 function 定义了如何访问数据,而不是如何更改数据。
Since the __str__
for the builtin User
model returns the username, you can also work with:由于内置
User
__str__
的 __str__ 返回用户名,您还可以使用:
class TutorAdmin(admin.ModelAdmin):
list_display = ('user_id', 'contact_number',
user)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.