根据模型过滤查询获取所有相关对象

时间:2017-07-29 09:49:33

标签: django django-rest-framework

尝试获取所有贷款清单以及与该特定贷款相关联的相关地址。

模特:

class LoanDetail(models.Model):
    job_no = models.AutoField('Job No', primary_key=True)
    loan_account_no = models.CharField('Loan account No', blank=True, max_length=128)
    job_status = models.IntegerField('Job Status', choices=JOB_STATUS, default=1, db_index=True)
    applicant_type = models.IntegerField('Applicant type', choices=APPLICANT_TYPE, default=1, db_index=True)
    customer_name = models.CharField('Customer Name', max_length=128)

class LoanUserAddress(models.Model):
    loan = models.ForeignKey(LoanDetail, on_delete=models.CASCADE, related_name="loanuser")
    address_type = models.ForeignKey(AddressType)
    house_name = models.CharField('House/Flat/Name', max_length=128)
    street = models.CharField('Street', max_length=128)
    area = models.CharField('Area/Location', max_length=128)

的观点:

class SearchLoan(APIView, ResponseViewMixin):

    def get(self, request, *args, **kwargs):
        loan = kwargs['loan'];
        address = LoanDetail.objects.filter(loan_account_no__in=[loan])

这只返回贷款详细信息,我如何获得所有地址以及贷款细节。

我希望回复如此 {'loan_account_no': '12412412421', 'customer_name': 'Ravi' , address: [ {'id': 1, 'house_name': 'Some aadress'}, {'id': 2, 'house_name': 'Some aadress 2'}, {'id': 3, 'house_name': 'Some aadress 3'}] }

1 个答案:

答案 0 :(得分:0)

如果您只想要一组负载的地址

addresses = LoanUserAddress.objects.filter(loan__loan_account_no__in=[loan])

如果您想要一份包含地址的贷款清单,请获取与您一样的贷款清单

loans = LoanDetail.objects.filter(loan_account_no__in=[loan])

并且对于查询集中的每个项目,您可以访问属性loanuser,该属性将是此贷款的地址列表。其中loanuser是ForeignKey字段的related_name

for loan_item in loans.all():
    print(loan_item.loanuser)