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

django ORM 没办法指定 Subquery 的字段进行 join 吗?

  •  
  •   wuwukai007 · 2022-02-17 14:43:20 +08:00 · 2636 次点击
    这是一个创建于 770 天前的主题,其中的信息可能已经有所发展或是发生改变。
    select *
    from user inner join
             (select login_id from account where created_time >='xxx') t1
             on t1.login_id = user.id; 
    
    • 如果能 构造一个 subquery ,然后可以 User.objects.filter(id=Subquery.c.login_id)
    • 现在 django 不支持 subquery.c.field 这种方式。
    5 条回复    2022-02-17 16:59:51 +08:00
    krixaar
        1
    krixaar  
       2022-02-17 15:07:29 +08:00
    django 不能 id__in 么
    Aganzo
        2
    Aganzo  
       2022-02-17 15:09:22 +08:00
    user_ids = Account.objects.filter(created_time__gt='xxx').values_list('login_id',flat=True).distinct()
    User.objects.filter(id__in=user_ids)
    应该是这个意思吧,queryset 会自动以子查询形式嵌套
    riiygh
        3
    riiygh  
       2022-02-17 15:19:18 +08:00
    没有看到你的 model 。假设 account 有外键 user ,可以这样试试:User.objects.filter(account__created_time__gte='xxx').all()
    wuwukai007
        4
    wuwukai007  
    OP
       2022-02-17 16:09:14 +08:00
    @Aganzo @riiygh
    不是这个意思,我想要做的是 join 一个自己构造出来的子查询,没有外键,就是 join 一个子查询
    krixaar
        5
    krixaar  
       2022-02-17 16:59:51 +08:00
    @wuwukai007 #4 2 楼写法等同于
    select * from user where id in (select login_id from account where created_time >= 'xxx')
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1007 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 19:29 · PVG 03:29 · LAX 12:29 · JFK 15:29
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.