如何根据多个表编写查询?

时间:2017-02-17 05:05:18

标签: django python-2.7

我想要贷款人的详细信息,其国家,地位,宗教,职业等于借款人的详细信息,即(州,地区,宗教,专业)

这是借款人models.py

class Borrower(models.Model):
    district = models.TextField(blank=True)
    state = models.TextField(blank=True)
    profession = models.TextField(blank=True)
    religion = models.TextField(blank=True)

这是Lenders models.py

class LenderStateDistrict(models.Model):
    lenderId = models.CharField(max_length=5)
    state = models.CharField(max_length=50,**optional)
    district = models.CharField(max_length=50,**optional)

class LenderReligion(models.Model):
    lenderId = models.CharField(max_length=5)
    religion = models.CharField(max_length=50, **optional)

class LenderMultipleProfessions(models.Model):
    lenderId = models.CharField(max_length=5)
    profession = models.CharField(max_length=50,**optional)

views.py

@api_view(['GET'])
def xyz(request):
   borrower1= Borrower.objects.get(id =1)
   city = borrower1.district
   state = borrower1.state
   profession = borrower1.profession
   religion = borrower1.religion

我得到了借款人的所有要求,然后如何根据这三个表进行查询,即; LenderStateDistrict,LenderReligion,LenderMultipleProfessions,如果借款人所在地区,州,宗教,行业等于贷方那么它应该给出详细信息如何查询呢?

2 个答案:

答案 0 :(得分:0)

您的模型存在根本问题。它们彼此无关。关系数据库管理系统的强大之处在于建立关系!

  

Django提供了定义三种最常见数据库类型的方法   关系:多对一,多对多和一对一。

https://docs.djangoproject.com/en/1.10/topics/db/models/#relationships

至少你需要在借款人和贷款人之间创建一个外键。但如果用户可以借用多个贷方

,则可能需要成为ManyToMany关系

答案 1 :(得分:0)

由于@ e4c5提到您的模型存在问题,请尝试将模型相互关联,以便更轻松地编写查询。

尝试以这种方式实现:

class District(models.Model):
    field1 = models.CharField(max_length=255)
    field2 = models.CharField(max_length=255)

class Religion(models.Model):
        field1 = models.CharField(max_length=255)
        field2 = models.CharField(max_length=255)

class Profession(models.Model):
        field1 = models.CharField(max_length=255)
        field2 = models.CharField(max_length=255)

根据您的问题,这应该是您的基本模型,然后您可以通过以下方式在贷方和借方表中引用这些模型:

class Lender(models.Model):
        district = models.ForeignKey(District, related_name="lender_district")
        profession = models.ForeignKey(Profession, related_name="lender_profession")
        religion = models.ForeignKey(Religion, related_name="lender_region")

class Borrower(models.Model):
        district = models.ForeignKey(District, related_name="borrower_district")
        profession = models.ForeignKey(Profession, related_name="borrower_profession")
        religion = models.ForeignKey(Religion, related_name="borrower_region")

这样您就可以实现所需的查询。假设您想要访问属于区域的借款人和贷方的详细信息,其中field1 =“xyz”,您必须简单地写一下:

lenders = Lender.objects.filter(district__field1="xyz")
borrowers = Borrower.objects.filter(district__field1="xyz")

更简单的方法是:

district = District.objects.get(field1="xyz")  # get district
lenders = Lender.objects.filter(district=district)  # Get Lenders
borrowers = Borrower.objects.filter(district=district)  # Get Borrowers

如果贷款人和借款人有多个学区,宗教或专业,您也可以实施ManyToMany关系。