为什么django ORM的“save”方法不返回保存的对象? [英] Why does django ORM's `save` method not return the saved object?

查看:666
本文介绍了为什么django ORM的“save”方法不返回保存的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对这种设计决策背后的推理有何见解?在我看来,拥有 obj.save() return 某些,只有好处(如方法链接),没有缺点。

解决方案

在Python中通常认为主要影响现有对象的功能返回自己的功能。例如, sorted(yourlist)返回排序列表,但 yourlist.sort()会将列表排在原位,不返回任何东西。



在单行上执行具有副作用的多个操作(而不是重点在返回值上的无副作用函数)不是很好的做法。代码在线路数量方面将更加紧凑,但是由于重要的副作用可能被埋在链条的中间,因此读数将变得更加困难。如果要使用方法链接,请使用链中开始时没有副作用的函数,然后在单个函数中具有副作用,如 .save()结束。



换句话说,在方法链中,链的开始是输入,链的中间转换输入(向下导航树,对输入进行排序,更改字符串的大小等),并且链的末端是具有副作用的功能部分。如果你在链中间埋下了副作用的方法,那么你的方法链实际上是不清楚的。


Any insight into the reasoning behind this design decision? It seems to me that having obj.save() return something, has only benefits (like method chaining) and no drawbacks.

解决方案

It's generally considered good practice in Python to have functions that primarily affect existing objects not return themselves. For instance, sorted(yourlist) returns a sorted list but yourlist.sort() sorts the list in-place and does not return anything.

Performing multiple operations with side-effects (as opposed to no-side-effect functions where the focus is on the return value) on a single line is not really good practice. The code will be more compact in terms of number of lines, but it will be harder to read because important side-effects may be buried in the middle of a chain. If you want to use method chaining, use functions with no side effects in the beginning of the chain and then have a single function with a side effect like .save() at the end.

To put it another way, in a method chain, the beginning of the chain is the input, the middle of the chain transforms the input (navigating down a tree, sorting the input, changing case of a string etc) and the end of the chain is the functional part that does work with side-effects. If you bury methods with side-effects in the middle of the chain then it will be unclear what your method chain actually does.

这篇关于为什么django ORM的“save”方法不返回保存的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆