Django 管理站点:如何包含条件字段?
我想知道是否可以在django中添加一些条件字段。 假设我有一个类别模型,其中包含 ID、名称和描述字段。 我想要的是在我的产品模型中添加一个多对多字段,将其与类别 ID 模型链接起来......并作为帮助参考显示该类别的名称是什么。 我知道我可以将其链接到类别名称,但我的真实场景有点复杂,我确实需要根据另一个字段中的选择显示第二个字段!
非常感谢!
I wonder if is it possible to add some conditional fields in django.
Say I have a category model which has an ID, name and description fields.
What I would like is to add a many-to-many field in my Product model that links it with the Category ID model... and as a helping reference show what the name of that Category would be.
I know I could just link it to the category name, but my real scenario is a bit more complex and I would really need to display a second field based on the selection in another !
Many thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
那不是条件字段。如果我理解正确的话,您真正需要的只是自定义相关项目的显示,以便它显示
name
字段而不是原始 ID。幸运的是,如果您在 Category 模型上定义一个 __unicode__ 方法,Django 将默认执行此操作,该方法返回您想要显示的值而不是 ID。That's not a conditional field. If I understand you correctly, all you really need is to customise the display of the related item, so that it shows the
name
field rather than the raw ID. Luckily, that is what Django will do by default if you define a__unicode__
method on the Category model, which returns the value you want to display instead of the ID.除了丹尼尔的回答之外:如果您只想自定义 ModelChoiceField 中对象的表示(并且通常不更改它,那么您将使用 __unicode__ 方法执行此操作) :字段类有方法
label_from_instance
,它默认返回对象的 unicode 值,但您可以根据需要重写它:In addition to Daniel's answer: If you just want to customize the representation of the objects in a
ModelChoiceField
(and not change it in general what you would do with the__unicode__
method): The field class has methodlabel_from_instance
, which returns by default the object's unicode value, but you can override it as you like: