如何在Django应用程序中联接两个mysql表

2024-05-12 13:03:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我的MySQL数据库中有两个表:

第一个表:用于订户(id、name、area、subscriberNumber、phoneNumber)

第二张表:用于按月付款(id、subscriberNumber、month、year、amount、discount、fine、billNumber)

我有一个HTML页面,其中的订户列表。每当管理员单击其中一个订阅者时,用户的详细信息是显示。但是目前我只能显示用户详细信息(从第一个表)。我希望页面显示他/她全年完成的付款列表(从第二个表)。我想连接这些表,并在一个HTML页面中显示两个表的详细信息。在

这是显示中第一个表的数据的代码视图.py在

@login_required
def userDetail(request, id=None):
    instance = get_object_or_404(Subscribers.objects.using('db2'), id=id)
    context = {
        "Name": instance.name,
        "instance": instance,
    }
    return render(request, 'userDetail.html', context)

如何在同一页面上显示用户完成的付款及其详细信息?在

在模型.py在

^{pr2}$

Tags: instance用户namepyid列表requesthtml
2条回答

要显示用户的付款,可以使用:

instance = get_object_or_404(Subscribers.objects.using('db2'), id=id)
try:    
    payment_info = Payments.objects.using('db2').get(subsNumber=instance.subsNumber)
except Payments.DoesNotExist:
    payment_info = None
context = {
    "Name": instance.name,
    "instance": instance,
    "payment": payment_info
}

为什么要用这么多的困惑??在

这样做吧

instance = Subscribers.objects.using('db2').get(id=id)
payment_info = Payments.objects.using('db2').get(subsNumber=instance.subsNumber)
context = {
    "Name": instance.name,
    "instance": instance,
    "payment": payment_info
}

相关问题 更多 >