django多级多对一查询数据检索

时间:2017-08-16 09:36:16

标签: python django

我有点复杂的数据库模型结构,见下文(仅结构)

class Service(models.Model)
    fields .....

class ServiceBillPost(models.Model):
    service = models.ForeignKey(Service, related_name='service_bill_posts')

class Payment(models.Model):
    bill_post = models.OneToOneField(ServiceBillPost)
    mode = models.PositiveSmallIntegerField(choices=PAYMENT_MODE, default=0)

PAYMENT_MODE = (
(0, 'Cash'),
(1, 'bKash'),
(2, 'CreditCard'),
(3, 'Cheque'),
(4, 'Company'),
)

现在我想要提取ServiceBillPost Service payment mode company的所有service_id

我有 service = Service.objects.get(pk=service_id) ,比如1,

然后我得到了那项服务,

service_bill_post = service.service_bill_post.all()

然后获得所有服务账单,

payment mode

但是在这里我如何使用django ORM根据上面给出的关系按mode Payment模型的{{1}}字段进行过滤?

2 个答案:

答案 0 :(得分:1)

你试过吗?:

service_bill_post = service.service_bill_post.filter(payment__mode='Cash')

*假设:

bill_post = models.OneToOneField(ServiceBillPost, related_name='payment')

答案 1 :(得分:0)

您可以使用filter()

service = Service.objects.get(pk=service_id)
service_bill_posts = service.service_bill_posts.filter(payment__mode='Company')