推荐学习书目
› 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 · May 13, 2019 · 3917 views
    This topic created in 2740 days ago, the information mentioned may be changed or developed.

    3 张表里的字段名一致

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

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

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

    ------

    第二种
    重新抽象 model,
    看业务需求用 proxy 模式或者直接用字段表示不同的类型,再分别 filter 出去
    KevinBu
    KevinBu
    OP
    May 14, 2019
    7
    多谢各位,现在用 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
    zibber
    May 14, 2019
    8
    关联查询 套两层
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   948 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 19:58 · PVG 03:58 · LAX 11:58 · JFK 14:58
    ♥ Do have faith in what you're doing.