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

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

  •  
  •   lanlanye ·
    laipz8200 · 2021-09-07 21:01:59 +08:00 · 1450 次点击
    这是一个创建于 932 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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 条回复    2021-09-08 09:10:55 +08:00
    chaleaoch
        1
    chaleaoch  
       2021-09-07 21:37:08 +08:00
    group 的外键是 user?
    弄反了吧?

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

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

    @Zhuzhuchenyan 感谢,使用 select_related 完美解决了问题!
    @NotFoundEgg 谢谢,很有帮助!
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3258 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 11:43 · PVG 19:43 · LAX 04:43 · JFK 07:43
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.