V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
Nick2VIPUser
V2EX  ›  Python

能否从实际使用经验的角度谈谈 Django function-based views 和 class-based views 两种 View 的优缺点或使用场景?

  •  
  •   Nick2VIPUser ·
    nickliqian · 2017-12-12 11:36:05 +08:00 · 1547 次点击
    这是一个创建于 2320 天前的主题,其中的信息可能已经有所发展或是发生改变。
    1. function-based views (FBVs)
    def sprinkle_list(request):
    ____request = check_sprinkles(request)
    ________return render(request, "sprinkles/sprinkle_list.html", {"sprinkles": Sprinkle.objects.all()})

    2. class-based views (CBVs)
    class SprinkleDetail(DetailView):
    ____model = Sprinkle
    ____def dispatch(self, request, *args, **kwargs):
    ________request = check_sprinkles(request)
    ________return super(SprinkleDetail, self).dispatch(request, *args, **kwargs)

    缩进表示不出来。。。用下划线替代了。。
    vicalloy
        1
    vicalloy  
       2017-12-12 13:51:24 +08:00   ❤️ 1
    我用 function-based views 更多一些。
    大多情况下 function-based views 数据流更清晰一些。
    不过 function-based views 的扩展性比较差,写通用的 views 会有些困难。

    就上面的场景来说,我觉得都可以,主要看习惯。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2839 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 11:33 · PVG 19:33 · LAX 04:33 · JFK 07:33
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.