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

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

问题描述

对这个设计决定背后的推理有什么见解吗?在我看来,让 obj.save() 返回 something,只有好处(如方法链)而没有缺点.

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.

推荐答案

通常认为 Python 中的好做法是让主要影响现有对象的函数返回自身.例如,sorted(yourlist) 返回一个排序列表,但 yourlist.sort() 对列表进行就地排序并且不返回任何内容.

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.

在一行上执行多个有副作用的操作(与无副作用函数相反,重点是返回值)并不是很好的做法.代码在行数方面会更紧凑,但会更难阅读,因为重要的副作用可能隐藏在链的中间.如果您想使用方法链,请在链的开头使用没有副作用的函数,然后在末尾使用一个具有副作用的函数,例如 .save().

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天全站免登陆