多对多字段的自定义管理

发布于 2024-12-27 00:56:04 字数 479 浏览 1 评论 0原文

我有一个模型 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 技术交流群。

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

发布评论

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

评论(1

动次打次papapa 2025-01-03 00:56:04

我想您可能对 Admin Inlines 表单感兴趣。

在这种情况下,您需要删除 ManyToMany 字段并添加
将外键字段添加到您的答案模型中,然后告诉管理员
将“内联”管理表单添加到您的问题管理视图中。

models.py

class Question(models.Model):
    ...


class Answer(models.Model):
    question = models.ForeignKey(Question)
    text = models.TextField()
    coefficient = models.IntegerField()

admin.py

class AnswerInline(admin.StackedInline):
    model = Answer


class QuestionAdmin(admin.ModelAdmin):
    inlines = [AnswerInline,]

这应该完全符合您的要求。

在问题对象中,您将有一个“answer_set”对象,其行为类似于
多对多处理程序。

以下示例说明如何获取包含与您的问题相关的所有答案的查询集。

my_question.answer_set.all()

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

class Question(models.Model):
    ...


class Answer(models.Model):
    question = models.ForeignKey(Question)
    text = models.TextField()
    coefficient = models.IntegerField()

admin.py

class AnswerInline(admin.StackedInline):
    model = Answer


class QuestionAdmin(admin.ModelAdmin):
    inlines = [AnswerInline,]

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.

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