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
achilles111
V2EX  ›  Python

django 前后端数据映射转换问题

  •  
  •   achilles111 · 2020-02-27 11:16:25 +08:00 · 2079 次点击
    这是一个创建于 1531 天前的主题,其中的信息可能已经有所发展或是发生改变。
    django+vue。数据库中一个字段有固定三个取值。例如分别是 增加、删除、修改。我在数据库中存放的时候是对应英文 add delete modify。前端界面展示的是汉字(也就是增加、删除、修改)。
    那么我在后端从数据库里取出数据的时候,是英文,必须转换一遍传到前端,才能直接使用。如果前端数据有更新,传回来,那我把新的数据存入数据库时,又需要转换一遍。
    django 自带模板中好像可以自动转换写了 choice 的字段,但是现在前端是 vue,就没法儿用。目前都是在后端用字典做映射。
    请问各位大佬,有没有更快捷的转换映射方式。
    6 条回复    2020-02-28 10:26:39 +08:00
    chenstack
        1
    chenstack  
       2020-02-27 11:27:14 +08:00
    前端做映射,传回后端用对应英文
    wuwukai007
        2
    wuwukai007  
       2020-02-27 11:30:59 +08:00
    这应该前端做,个人觉得
    superrichman
        3
    superrichman  
       2020-02-27 11:40:06 +08:00
    既然前后端都分离了,前端的展示应该让前端去做吧。
    blessyou
        4
    blessyou  
       2020-02-27 12:34:59 +08:00 via Android
    前端做 我怕你到时候还得来一套繁体 map
    siteshen
        5
    siteshen  
       2020-02-27 12:39:15 +08:00
    在后端做的话,可以额外加个字段,API 调用时用原来值,展示时用 display_xxx 属性。

    # model:
    class Post:
    category = models.CharField(max_length=100, choices=(...))


    # API 设计:
    {"category": "finance | art", "display_category": "财经 | 艺术"}

    # 辅助函数,从 choices 里解析出对应的值:
    def get_display_value(post, field='category'):
    # model = post.__class__.model
    # choices = ...
    # [c[1] c for c in choices if c[0] === getattr(post, field')][0]


    # 进一步优化的话,可以写个 decorator 完成转换工作:
    @display_fields('category')
    def list_post(request, response):
    # 原来的逻辑

    # 以上伪代码未考虑错误处理,请自行完善。
    achilles111
        6
    achilles111  
    OP
       2020-02-28 10:26:39 +08:00
    感谢诸位大佬,目前暂定让前端做转换了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1006 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 20:41 · PVG 04:41 · LAX 13:41 · JFK 16:41
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.