多对多字段的自定义管理
我有一个模型 Question
,它可以有多个 Answer
实例,每个实例都有一个给定的系数。
我想要的是一个管理员,我可以在其中添加任意数量的答案,并且每次添加答案时都会创建一个新答案。
我尝试使用多对多字段,如下所示,但默认管理是多重选择,其中包含数据库中的所有答案。
理想情况下,我想要的是我的问题管理中的“添加答案”按钮,这将允许我创建一个新答案并将其添加到我的问题中。
我怎样才能实现这个目标?
谢谢
class Question(models.Model):
answer = models.ManyToManyField(Response)
class Answer(models.Model):
text = models.TextField()
coefficient = models.IntegerField()
I have a model Question
which can have several Answer
instances, each one with a given coefficient.
What I want is an admin in which I can add as many answers as I want, and creating a new one everytime one is added.
I tried with a many-to-many field, as shown below, but the default admin is a multiple select with all the answers in the db.
What I would like ideally is a button "add answer" in my Question admin, which would allow me to create a new answer and add it to my question.
How can I achieve this?
Thanks
class Question(models.Model):
answer = models.ManyToManyField(Response)
class Answer(models.Model):
text = models.TextField()
coefficient = models.IntegerField()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想您可能对 Admin Inlines 表单感兴趣。
在这种情况下,您需要删除 ManyToMany 字段并添加
将外键字段添加到您的答案模型中,然后告诉管理员
将“内联”管理表单添加到您的问题管理视图中。
models.py
admin.py
这应该完全符合您的要求。
在问题对象中,您将有一个“answer_set”对象,其行为类似于
多对多处理程序。
以下示例说明如何获取包含与您的问题相关的所有答案的查询集。
I think you may be interested in Admin Inlines form.
In this case you need to remove the ManyToMany field and add
a ForeignKey field to your Answer model and then tell the admin
to add an 'inline' admin form to your Question admin view.
models.py
admin.py
This should do exactly what you asked for.
In the Question object you will have a 'answer_set' object which behave like
a ManyToMany handler.
The following example explain how to get a queryset containing all the answer related to your question.