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

Django 如何一次查询 3 张表?

  •  
  •   KevinBu · 2019-05-13 09:21:29 +08:00 · 2965 次点击
    这是一个创建于 1802 天前的主题,其中的信息可能已经有所发展或是发生改变。

    3 张表里的字段名一致

    我在 Googld 搜索的结果都是查询 2 张表的

    请问如何一次查多张表呢?

    8 条回复    2019-05-14 16:58:24 +08:00
    NaVient
        1
    NaVient  
       2019-05-13 09:27:54 +08:00
    join 操作?没有外键请直接用 raw 写 sql
    awanabe
        2
    awanabe  
       2019-05-13 10:22:21 +08:00
    flask 里面可以多个 outerjoin 串联 实现多表查询
    gjquoiai
        3
    gjquoiai  
       2019-05-13 11:07:43 +08:00   ❤️ 1
    emm union ?
    wd
        4
    wd  
       2019-05-13 12:40:05 +08:00 via iPhone
    django 里面你应该是通过 model 的关系来查询,如果你真想一次查,那就只能写 join
    freakxx
        5
    freakxx  
       2019-05-13 14:23:33 +08:00
    第一种办法
    1 分别查询
    2 用 chains 连接起来
    3 如果是 drf,建个自定义 serializer 序列化

    ------

    第二种
    重新抽象 model,
    看业务需求用 proxy 模式或者直接用字段表示不同的类型,再分别 filter 出去
    anshengme
        6
    anshengme  
       2019-05-13 18:17:17 +08:00
    KevinBu
        7
    KevinBu  
    OP
       2019-05-14 09:42:53 +08:00
    多谢各位,现在用 union 解决了这个问题,官方文档里也有介绍

    union (* other_qs,all = False )
    使用 SQL 的 UNION 运算符来组合两个或多个 QuerySets 的结果 。例如:
    >>> qs1.union(qs2, qs3)

    https://docs.djangoproject.com/en/1.11/ref/models/querysets/#django.db.models.query.QuerySet.union
    zibber
        8
    zibber  
       2019-05-14 16:58:24 +08:00
    关联查询 套两层
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3364 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 12:00 · PVG 20:00 · LAX 05:00 · JFK 08:00
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.