如何在 Django 中创建查找?
我有一个问题模型& 表单,此模型中的字段之一是 userid=ForeignKey(User),这在问题模型上运行得非常好,我能够从下拉列表中选择用户。
但是,当我想列出模型中的问题时,有点棘手,这是从用户表中查找用户名的最佳方式? 因为此时我无法使用下拉菜单!
我想要一个简单的东西,例如
问题标题 询问者:查找用户名
I have a Question model & Form, one of the fields in this model is userid=ForeignKey(User), this Works perfectly well on the Question Model, am able to pick the user from a drop down.
But kind a tricky when i want to list the question from the model, which is the best way to lookup the user name from the Users table? becouse at this point i cant have the dropdown!
I want to have a simple thing e.g.
Question Title
asked by:lookup user Name
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的字段名称(
userid
而不是user
)让我认为您可能对 Django 的ForeignKey
的行为感到困惑。如果您定义这样的模型:
然后将
Question
实例化为question
:看起来您可能期望
question.userid
成为用户的主键,而不是它实际的内容:User
实例本身。 当您访问question.userid
时,会执行数据库查找,但它是由 Django 使用question.userid_id
的值自动完成的。 我会将userid
字段重命名为user
以避免混淆。这样一来,我认为您要做的就是列出问题及其相关用户。 如果是这种情况,请在模板中执行以下操作:
The name of your field (
userid
instead ofuser
) makes me think that you may be confused about the behavior of Django'sForeignKey
.If you define a model like this:
And then instantiate a
Question
asquestion
:It looks like you may be expecting
question.userid
to be the user's primary key, rather than what it actually is: theUser
instance itself. When you accessquestion.userid
, a database lookup is performed, but it's done automatically by Django using the value ofquestion.userid_id
. I would rename theuserid
field touser
to avoid confusion.With that out of the way, I think what you are trying to do is list the questions along with their associated users. If that's the case, do something like this in your template:
我发现你的问题含糊不清。 如果您想获取与给定
user_name
的特定User
实例相关的所有Question
实例,您可以这样做:如果您已经有一个
User
实例(例如,保存在一个名为user
的变量中),并且想要获取与其相关的所有Question
对象,您可以获取那些有:I find your question vague. If you want to fetch all
Question
instances that are related to a particularUser
instance given auser_name
, you can do thus:If you already have a
User
instance (held, say, in a variable calleduser
) and would like to fetch allQuestion
objects related to it, you can get those with: