如何在我的Django应用程序中连接两个mysql表

时间:2017-07-06 04:01:52

标签: python mysql django

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

第一张表:对于订阅者(id,name,area,subscriberNumber,phoneNumber)

第二张表:每月付款(id,subscriberNumber,month,year,amount,discount,fine,billNumber)

我有一个HTML页面,其中包含订阅者列表。每当管理员点击其中一个订阅者时,就会显示用户的详细信息。但是目前我只能显示用户详细信息(来自第一个表)。我希望该页面显示他/她全年所做的付款清单(从第二张表开始)。我想加入表格并在一个HTML页面中显示表格的详细信息。

这是显示views.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)

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

Models.py

from __future__ import unicode_literals
from django.db import models
from django.core.urlresolvers import reverse

class Subscribers(models.Model):
    name = models.CharField(max_length=120)
    area = models.CharField(max_length=30)
    phoneNumber = models.CharField(max_length=10)
    installationCost = models.CharField(max_length=10)
    subsNumber = models.CharField(max_length=100)

    def get_absolute_url(self):
        return reverse("userDetail", kwargs={"id": self.id})


class Payments(models.Model):
    month = models.CharField(max_length=120)
    year = models.CharField(max_length=4)
    amount = models.CharField(max_length=10)
    discount = models.CharField(max_length=10)
    fine = models.CharField(max_length=10)
    billNumber = models.CharField(max_length=100)
    subsNumber = models.CharField(max_length=100)

    def get_absolute_url(self):
        return reverse("userDetail", kwargs={"id": self.id})

2 个答案:

答案 0 :(得分: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
}

答案 1 :(得分:1)

为什么要使用很多混乱?

改为执行此操作

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
}