Django - 内联表单和外键
我有一个应用程序,允许用户为项目创建估算。该估算包含基本的客户信息(姓名、地址、电话号码等)和我生成的自定义主键值。现在,我还有另外两个模型来列出该工作所需的估计产品和劳动力。这两个模型通过外键链接到“主”估计模型。对于这两个模型,我将使用内联表单集,因为默认情况下它们通过外键链接到另一个记录。
我想知道是否可以与两个内联表单同时创建主要估算(基本数据)记录?看起来它不起作用(嗯,我在让它工作时遇到了麻烦),因为两个内联表单集链接到的外键还不存在,因为它也只是创建的。
最好将其分为两步:步骤 1) 创建和创建保存基本数据(从而创建可链接的主键) 步骤 2) 添加产品和人工记录,通过主记录的外键将它们链接起来。这似乎是一个糟糕的 UI 设计(有两个步骤)。
想法?
谢谢!
I have an app that allows a user to create an estimate for a project. The estimate has the basic client information (name, address, phone number, etc.) and a custom Primary Key value that I generate. Now, I also have two other models for listing estimated products and labour needed for the job. These two models are linked to the "main" estimate model with a Foreign Key. For these two models I was going to use inline formsets since they, by default, link to another record via a foreign key.
I'm wondering if it is possible to create the main estimate (the basic data) record at the same time as the two inline forms? It seems like it wouldn't work (well, I'm having trouble making it work) since the foreign key that the two inline formsets are linked to doesn't exist yet because it is also just being created.
Would it be better to make this a two step process: Step 1) Create & save basic data (thereby creating the primary key that can be linked to) Step 2) Add product and labour records linking them by the foreign key of the main record. It just seems that this would be a poor UI design (having two steps).
Thoughts?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
事实上,这就是管理员(
django.contrib.admin
)对内联表单执行此操作的方式。如果您不想深入研究该代码,可以尝试使用 transactions 将所有数据库更改捆绑在一起,以便您可以在需要时将它们全部回滚。当然,这假设您的后端数据库支持事务。
This is, in fact, the way the admin (
django.contrib.admin
) does it for an inline form.If you don't feel like diving into that code, you could try to use transactions to bundle all the database changes together, so you can roll them all back if needed. This assumes your back-end database supports transactions, of course.