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

django orm 中有没有拆分字段的方法

  •  
  •   chaleaochexist · 2019-06-21 10:58:31 +08:00 · 1581 次点击
    这是一个创建于 1761 天前的主题,其中的信息可能已经有所发展或是发生改变。
    找了半天没找到太合适的.
    伪 sql

    select name.split('/') from name_table;
    5 条回复    2019-06-21 13:28:11 +08:00
    37Y37
        1
    37Y37  
       2019-06-21 12:30:18 +08:00
    先查出来再 split,split 放在程序做
    XiaoxiaoPu
        2
    XiaoxiaoPu  
       2019-06-21 13:13:07 +08:00
    重载 CharField,自定义字段呗
    Vegetable
        3
    Vegetable  
       2019-06-21 13:20:55 +08:00
    搞不懂你想干什么,你想取出来就是分好的?你可以给 model 定义方法获取吧,何必在数据库层操作?
    chaleaochexist
        4
    chaleaochexist  
    OP
       2019-06-21 13:23:45 +08:00
    @Vegetable
    @XiaoxiaoPu
    谢谢,只是好奇,最后用的是#1 的方法.
    Vegetable
        5
    Vegetable  
       2019-06-21 13:28:11 +08:00   ❤️ 1
    class AModel(models.Model):

    field = models.Charfield(...)

    @property
    def splited_field(self):
    if self.field:
    return self.field.split("/")[0]
    else:
    return ""

    没有缩进凑合看一下,这种类似的逻辑我会直接些在 model 层写好,业务层直接调用方法来获取处理好的数据.
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5549 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 08:34 · PVG 16:34 · LAX 01:34 · JFK 04:34
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.