两个外键返回给 User 并在 Admin 中调用 get_full_name
请教两个问题:
我需要两个外键返回给用户,一个用于作者,一个用于共同作者。我已通过将 lated_name
设置为等于 + 来进行管理,但不确定这是否是明智的方法或最好的方法。想法还是指点?
当通过 django 管理为此模型创建添加条目时,作者选择的是 john_smith 等名称。我应该从哪里调用 get_full_names() 以显示全名而不是带下划线的用户名?谢谢。
from django.contrib.auth.models import User
from django.db import models
class Books(models.Model):
title = models.CharField()
author = models.ForeignKey(User)
coauthor = models.ForeignKey(User, related_name='+')
凯文
Two questions please:
I need two foreign keys back to User, one for author and one for coauthor. I have managed by setting related_name
equal to + but am not sure if this is smart or the best way. Thoughts or pointers?
When making an add entry via the django admin for this model, the author choices are names like john_smith, etc. Where would I call get_full_names() from in order to display full names rather than usernames with underscores? Thanks.
from django.contrib.auth.models import User
from django.db import models
class Books(models.Model):
title = models.CharField()
author = models.ForeignKey(User)
coauthor = models.ForeignKey(User, related_name='+')
Kevin
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会将相关名称更改为更容易理解的值 - 例如
books_where_coauthor
并添加类似的books_where_author
,这样您就可以通过以下方式获取相关书籍:theuser.books_where_author.all()
等关于您的管理查询,您将获取用户名,因为这是 User 的默认
__unicode__()
方法吐出的内容。除非您想破解您的 contrib.auth.models 文件(不推荐),否则我建议在管理中使用自定义模型表单,并手动设置 ModelChoiceField,通过对该字段进行子类化并创建一个自定义字段来使用
get_full_name 呈现其小部件
如果可能的话,或者通过此代码段之类的方式来完成。也就是说,我确信有一种更简单的方法可以做到这一点,但我忘记了。该死。I would change the related name to a value that is more intelligible - such as
books_where_coauthor
and also add a similar one ofbooks_where_author
as then you can get the relevant books by going fromtheuser.books_where_author.all()
etcRegarding your Admin query, you're getting the username because that's what the default
__unicode__()
method of User spits out.Unless you'd like to hack your contrib.auth.models file (not recommended), I'd suggest using a custom modelform in the admin, and manually setting the names of the choices in the ModelChoiceField, either by subclassing that field and making a custom one that renders its widget with
get_full_name
if possible, or do it via something like this snippet. That said, I am sure there's a simpler way to do that, but I've forgotten. Dangit.关于我的问题的第二部分(在表单的 ChoiceField 中显示全名而不是用户名),我发现 此链接 只是票证:
With regard to the second part of my question (displaying full names instead of usernames in the ChoiceField of a form), I found this link to be just the ticket: