推荐学习书目
› 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 · Feb 17, 2022 · 4000 views
    This topic created in 1688 days ago, the information mentioned may be changed or developed.
    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 replies  •  2022-02-17 16:59:51 +08:00
    krixaar
        1
    krixaar  
       Feb 17, 2022
    django 不能 id__in 么
    Aganzo
        2
    Aganzo  
       Feb 17, 2022
    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  
       Feb 17, 2022
    没有看到你的 model 。假设 account 有外键 user ,可以这样试试:User.objects.filter(account__created_time__gte='xxx').all()
    wuwukai007
        4
    wuwukai007  
    OP
       Feb 17, 2022
    @Aganzo @riiygh
    不是这个意思,我想要做的是 join 一个自己构造出来的子查询,没有外键,就是 join 一个子查询
    krixaar
        5
    krixaar  
       Feb 17, 2022
    @wuwukai007 #4 2 楼写法等同于
    select * from user where id in (select login_id from account where created_time >= 'xxx')
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   773 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 21:00 · PVG 05:00 · LAX 14:00 · JFK 17:00
    ♥ Do have faith in what you're doing.