推荐学习书目
› 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
lanlanye
V2EX  ›  Python

[求助帖] Django ORM 的联表查询问题

  •  
  •   lanlanye ·
    laipz8200 · Sep 7, 2021 · 2455 views
    This topic created in 1845 days ago, the information mentioned may be changed or developed.

    Django3.2

    数据库没有做外键,但是在 model 定义的时候写了外键关系,举例来说

    class User(model.Model):
        id = ...
        name = ...
    
    
    class Group(model.Model):
        user = model.ForeignKey(User, db_column='user_id', ...)
        ...
    

    之后我在使用 drf 时定义了这样一个 serializer

    class GroupSerializer(serializers.Serializer):
        user_name = serializers.CharField(source='user.name')
    

    结果发现 Django 的查询方法是先查 Group 表,再根据其中的 user_id 一条一条去查 name ,有没有什么办法能让它直接使用 JOIN 获取到序列化器需要的结果?

    4 replies  •  2021-09-08 09:10:55 +08:00
    chaleaoch
        1
    chaleaoch  
       Sep 7, 2021
    group 的外键是 user?
    弄反了吧?

    另外, serializers.Serializer 和 Model 是没有发生关系的. 除非你用的是 ModelSerializer.

    你在整理一下你的问题.
    Zhuzhuchenyan
        2
    Zhuzhuchenyan  
       Sep 8, 2021   ❤️ 1
    NotFoundEgg
        3
    NotFoundEgg  
       Sep 8, 2021   ❤️ 1
    今天刚看到一个 N+1 查询问题的博客 不知道是不是你说的这个问题
    https://www.cnblogs.com/zknublx/p/6197377.html
    lanlanye
        4
    lanlanye  
    OP
       Sep 8, 2021
    @chaleaoch 实例是随手写的,并不是一个合理的用户组模型,只是想表达存在这样的关联关系。晚上提问的时候没考虑太多,产生歧义了,抱歉。

    @Zhuzhuchenyan 感谢,使用 select_related 完美解决了问题!
    @NotFoundEgg 谢谢,很有帮助!
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2697 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 15:00 · PVG 23:00 · LAX 08:00 · JFK 11:00
    ♥ Do have faith in what you're doing.