两个外键返回给 User 并在 Admin 中调用 get_full_name

发布于 2024-10-01 12:09:29 字数 496 浏览 2 评论 0原文

请教两个问题:

我需要两个外键返回给用户,一个用于作者,一个用于共同作者。我已通过将 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

ま柒月 2024-10-08 12:09:29

我会将相关名称更改为更容易理解的值 - 例如 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 of books_where_author as then you can get the relevant books by going from theuser.books_where_author.all() etc

Regarding 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.

绝對不後悔。 2024-10-08 12:09:29

关于我的问题的第二部分(在表单的 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:

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文