3

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

 2 years ago
source link: https://www.v2ex.com/t/800487
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

V2EX  ›  Python

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

  lanlanye · 22 分钟前 · 24 次点击

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 获取到序列化器需要的结果?


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK