request.user.is_authenticated的弊端

user = request.user if request.user.is_authenticated else None
想请问一下,上述代码有什么弊端吗?
领导说不让这么写。不明白原因

(I really hope Google translate has done a good job with this.)

Alone, there are no drawbacks to that line of code. Problems might occur other places in your code when you try to use the user object.

仅此一行代码就没有缺点。 当您尝试使用用户对象时,代码中的其他地方可能会出现问题。

user = request.user if request.user.is_authenticated else None
请不要这样写。请总是在有需要地方写 if request.user.is_authenticated 。不要让 user 为 None
整个项目中,所有地方都不允许用 None 表示未登录。
请告诉我为什么不能这么写的原因.

There will always be a request.user object.

All the rest of the code (your code and “Django” code) relies upon the assumption that request.user exists. (Someone is making the request, even if that someone is “AnonymousUser”.)
There are other function calls that will try to access attributes on the user object. Those function calls will not work if user is set to “None”.

总会有一个request.user对象。

其余所有代码(您的代码和“ Django”代码)都依赖于request.user存在的假设。 (即使有人是“ AnonymousUser”,也有人在发出请求。)
还有其他函数调用将尝试访问用户对象上的属性。 如果用户设置为“无”,则这些功能调用将不起作用。

user = request.user if request.user.is_authenticated else AnonymousUser()
您认为这样写合理吗?

It is reasonable, but totally unnecessary.

See the docs on request.user. Request.user is set to AnonymousUser if the person is not logged in.

If you need a local reference to request.user, then user = request.user is all you need.

这是合理的,但完全没有必要。

请参阅request.user上的文档。 如果此人未登录,则Request.user设置为AnonymousUser。

如果您需要对request.user的本地引用,则只需要user = request.user。