Django 中 reverse() 和 reverse_lazy() 的区别 [英] Difference between reverse() and reverse_lazy() in Django

查看:25
本文介绍了Django 中 reverse() 和 reverse_lazy() 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我们可以在 FBV 中使用 reverse() 和在 CBV 中使用 reverse_lazy().我知道我们必须在 CBV 中使用 reverse_lazy(),因为在导入文件时不会加载 url(参考:Reverse_lazy 和 URL 加载?)

I understand that we can use reverse() in FBV and reverse_lazy() in CBV. I understand that we have to use reverse_lazy() in CBV as the urls are not loaded when the file is imported (Ref: Reverse_lazy and URL Loading?)

我不明白的是:

当我们从 FBV 调用 reverse 时,url 是如何加载的?当我们在 Django 应用程序中导入 urls.py 顶部的视图时,urlpatterns 列表尚未评估.reverse() 如何用于 FBV 而不适用于 CBV?

How are the urls loaded when we call reverse from the FBV? As when we import the views at the top of the urls.py in a Django app, urlpatterns list is yet to be evaluated. How does reverse() for FBV work but not for CBV?

推荐答案

#importme.py
def a():
    print("FUNCTION HELLO")

class B():
    print("CLASS HELLO") 
    

>>> import importme
>>> CLASS HELLO

原因:类的创建过程涉及到执行类的主体.

The reason: The class creation process involves executing the body of the class.

类主体以exec(body, globals(), namespace) 的形式执行(大约).[...] 一旦类命名空间被填充执行类主体,通过调用创建类对象metaclass(name, bases, namespace, **kwds).

The class body is executed (approximately) as exec(body, globals(), namespace). [...] Once the class namespace has been populated by executing the class body, the class object is created by calling metaclass(name, bases, namespace, **kwds).

https://docs.python.org/3/reference/datamodel.html?highlight=metaclass#executing-the-class-body

我的原始答案文本.你可以忽略它 - 我只是把它留在里面,因为 mirek 的评论是对它的直接回应:

在导入时评估类属性.何时或如何发生这种情况的答案存在于 Python 导入系统的深处.

Class attributes are evaluated on import. The answer to when or exactly how that happens, resides within the depths of python's import system.

这篇关于Django 中 reverse() 和 reverse_lazy() 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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