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 dja开发者_如何学JAVAngo.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
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.
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:
精彩评论