python - django嵌套查询或连接两个表

标签 python django rest join django-rest-framework

我使用以下代码从“债务”表中列出了客户的债务。

但是,我想从“客户”表中查看具有相同 ID 号的客户的姓名。

我使用以下代码找到了我指定的人,但是;我无法打印到“Debts.objects.values ("customer ")”。

有没有简单的方法可以做到这一点?

感谢您的帮助。

class CustomerDetailDebtListAPIView(ListAPIView):
    serializer_class = DebtCreateSerializer

    def get(self, request):
        # get customer , customerKey
        obj_customer = Customer.objects.get(customer=85)
        field_object_customer = Customer._meta.get_field('customer')
        # field_value_customer = getattr(obj_customer, field_object_customer.attname)
        print(obj_customer)

        result = Debt.objects.values('customer') \
            .annotate(totalDebt=Sum('totalDebt'), receivedAmount=Sum('receivedAmount')) \
            .order_by('customer')
        return Response(result)

最佳答案

我假设客户是外键。您可以使用 __ 运算符访问相关表的字段。这如下面的代码所示

Debt.objects.all().annotate(totalDebt=Sum('totalDebt'), receivedAmount=Sum('receivedAmount')).order_by('customer').values('customer__surname')

from django.db.models import F
Debt.objects.all().annotate(totalDebt=Sum('totalDebt'), receivedAmount=Sum('receivedAmount'), surname=F('customer__surname')).order_by('customer').values('surname')

关于python - django嵌套查询或连接两个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58656843/

相关文章:

python - (Python新手求助)getch?

python - 用于 Python 的在线 IDE

android - ResultReceiver 无法幸免于屏幕旋转

python - 纯 Python 逆误差函数

python - SQLAlchemy 模型循环导入

python - 实现数据库范围功能的正确方法

java - 您可以在不使其无状态的情况下将 Spring Security 与 REST 服务一起使用吗?

c# - 如何将 POST 参数转换为 Action 参数

python - 使用 Django-datatable-view 不显示数据表

python - 变音符号