首页 > 解决方案 > Python Django 多级连接查询

问题描述

任务详细信息 我正在创建一个自定义 API,以根据提供的密钥信息从三个表中获取数据。

背景 详细说明,我有三个数据表 - Client、Account 和 Client_accounts,它们的结构如下所示:

Client
    ID           (Integer)       Primary Key
    display_name (varchar)

Accounts
    ID           (Integer)       Primary Key
    nickname     (varchar)   

Client_Accounts
    Client_ID    (Integer)       Foreign Key -> ID from client table   
    Account_ID   (Integer)       Foreign Key -> ID from accounts table

打算将客户端 ID 传递给我的 API,并希望获取该客户端拥有的所有帐户(和帐户名称)。

我试图复制的 SQL 查询如下所示:

select
    cl.id as client_id,
    cl.display_name,
    ac.id as account_id,
    ac.nickname as account_name
from
    datahub_clients         cl
    join
    datahub_client_accounts cl_ac
    on 
        cl.id=cl_ac.client_id
    join    
    datahub_accounts        ac
    on 
        cl_ac.account_id=ac.id
where
    cl.id=15
;

到目前为止完成 这是我用来获取客户帐户的内容:

##### For endpoint - get_client_name
@api_view(['GET', 'POST'])
@permission_classes((AllowAny,))
def get_client_name(request):
    try:
        if request.method == 'GET':   
            list_of_account_ids = Client_Accounts.objects.filter(client_id=request.GET['id']).values_list('account')
            needed_accounts = Accounts.objects.filter(id__in=list_of_account_ids).values('id','nickname')

            return Response({'requested client id':request.GET['id'],'identified client name': 'detailed info to go here'}, status=status.HTTP_200_OK)

        else:
          return Response({'status':'error','message': 'Facepalm moment!'}, status=status.HTTP_403_FORBIDDEN)

问题陈述

1) 在上面的代码中,我能够为 client_id 提取相关帐户,但是,我只能从帐户表中打印详细信息。我如何将客户信息也放入输出中(client_id、昵称 - 如 SQL 查询中所示)

2) SQL 'old_field_name AS some_new_name' 的 django 替代品是什么?在上面显示的数据表中,帐户和客户表都有一个“ID”列。我想将它们放在同一个 JSON 输出中并能够区分它们,我想重命名它们。

3)此时,我的查询集具有来自多个模型的字段成员。我如何序列化它们?我知道我需要编写一个基于两个模型的自定义序列化程序(例如上面显示的示例)。我对在 model= 部分和 meta: 部分中指定的内容感到困惑。

标签: djangodjango-rest-frameworkdjango-viewsdjango-querysetdjango-serializer

解决方案


推荐阅读