一次添加多个具有部分共享字段的模型实例

huangapple go评论112阅读模式
英文:

Add multiple instances of a model with some shared fields at once

问题

我正在尝试想出一种方法,允许用户在Django管理界面一次性添加多个特定模型的实例,但其中一些字段在它们之间共享。

示例模型:

class Something(models.Model):
    ref = models.ForeignKey(to="AnotherModel", on_delete=models.CASCADE)
    name = models.CharField(max_length=255)
    is_active = models.BooleanField(default=True)

我想要实现的是在Django管理界面中有一个页面,用户可以在其中只定义一次ref字段的值,然后添加和填充尽他想要的nameis_active字段,然后点击保存按钮,ref字段会自动重新使用,以创建与用户创建的nameis_active字段一样多的Something实例。

我知道Django的StackedInlineTabularInline,但我无法使用它们来实现上述功能。

谢谢。

英文:

I'm trying to come up with a way of allowing a user to add multiple instances of a specific model at once in Django Admin, but with some fields being shared between them.

Example model:

class Something(models.Model):
    ref = models.ForeignKey(to="AnotherModel", on_delete=models.CASCADE)
    name = models.CharField(max_length=255)
    is_active = models.BooleanField(default=True)

What I am trying to achieve is to have a page in Django Admin where the user would define the value of ref field only once, then add and populate as many name and is_active fields as he wants, press the Save button and the ref field would get automatically re-used to create as many Something instances as the user created with the name and is_active fields.

I know of Django's StackedInLine and TabularInLine, but I am not able to produce the above mentioned functionality with them, at all.

Thank you

答案1

得分: 3

class SomethingInline(admin.TabularInline):
model = Something
extra = 1

class AnotherModelAdmin(admin.ModelAdmin):
inlines = [SomethingInline]

这样你可以创建另一个模型实例并添加多个Something模型的内联项目。

英文:
class SomethingInline(admin.TabularInline):
    model = Something
    extra = 1

class AnotherModelAdmin(admin.ModelAddmin):
    inlines = [SomethingInline]

this way you can create another model instance and add multiple inline items of Something model.

huangapple
  • 本文由 发表于 2023年7月3日 18:10:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76603771.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定