如何保存 django 内联表单集的顺序?
在 Django 中,我在设置了 order_with_respect_to
的模型上使用带有 can_order = True
的内联表单集。我已经在前端设置了拖放操作,这会导致 Django 自动生成的 ORDER 表单字段(我已隐藏)发生变化以反映新订单。我已经验证我已将新订单正确发布到服务器,但 Django 似乎忽略它,并按原始顺序保存模型。数据库中自动创建的 _order
字段永远不会改变。
如何让 Django 使用表单集中指定的顺序保存模型?除了在表单集上调用 save()
之外,我还需要做任何特殊的事情吗?
In Django, I'm using an inlineformset with can_order = True
, on a model that has order_with_respect_to
set. I've set up drag and drop on the front end, which results in Django's autogenerated ORDER form fields (which I've hidden) changing to reflect the new order. I've verified I'm POSTing the new order correctly to the server, but Django seems to ignore it, and saves the models in the original order. The automatically-created _order
fields in the database never change.
How can I get Django to save the models using order specified in the formset? Do I need to do anything special other than calling save()
on the formset?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Evan Borgstrom 提出的解决方案不能与
can_delete=True
一起使用。这是我的解决方案,也适用于
can_delete=True
:Evan Borgstrom proposed solution does not work together with
can_delete=True
.Here is my solution that also works with
can_delete=True
:我遇到了同样的问题,在深入研究 Django 源代码后发现这是你需要自己做的事情。
我最初的实现看起来像这样:
但是,正如您所发现的,这并没有设置顺序。因此,我的实现现在看起来像:
在上面的示例中,“order_order”是我用来跟踪模型上的订单的字段。
另请记住,您需要指定模型的 Meta 类的“ordering”属性,以确保再次生成表单集时元素的顺序正确。
I had the same problem and after digging through the Django source figured that it's something you need to do on your own.
My original implementation looked something like this:
However, as you've found this doesn't set the ORDER. So instead my implementation now looks like:
In my example above 'order_order' is the field I'm using to track order on my models.
Also remember that you need to specify the 'ordering' attribute of your model's Meta class to ensure that when you generate the formset again the elements are in the correct order.