首页 > 解决方案 > 如何通过在 django 中加入两个表来获取数据?

问题描述

寻求帮助时卡住了,我是 python 和 django 的新手。有两个付款对应于一个订单,一个 COLLECTION 和多个 TRANSFER,我需要与一个方向为 COLLECTION 的订单相对应的付款,但尚未转移,以便我可以针对该订单启动 TRANSFER

模型.py

class Orders(models.Model):
    id= models.AutoField(primary_key=True)
    payment_gateway_code = models.CharField(max_length=20,choices=[('PAYTM','PAYTM')])
    is_active = models.BooleanField(default=True)

class Payments(models.Model):
    id = models.AutoField(primary_key=True)
    orders = models.ForeignKey(Orders, on_delete=models.CASCADE)
    direction = models.CharField(max_length=20,choices=[('COLLECTION','COLLECTION'), 
                                                        ('TRANSFER','TRANSFER')])
    settlement_status = models.CharField(max_length=50,blank=True, null=True,choices=[('YES','YES'), 
                                                                                       ('NO','NO')])
    is_active = models.BooleanField(default=True)

qualified_orders = Orders.objects.filter(payment_gateway_code='CASHFREE', 
                   Exists(Payments.objects.filter(order=OuterRef('pk'), direction='COLLECTION', 
                   settlement_status='YES')), ~Exists(Payments.objects.filter(order=OuterRef('pk'), 
                   direction='TRANSFER')))

但上面的查询不起作用

标签: pythondjangodjango-modelsdjango-viewsorm

解决方案


您可以按如下方式使用views.py

模型.py

class Orders(models.Model):
    id= models.AutoField(primary_key=True)
    payment_gateway_code = models.CharField(max_length=20,choices=[('PAYTM','PAYTM')])
    is_active = models.BooleanField(default=True)

class Payments(models.Model):
    id = models.AutoField(primary_key=True)
    orders = models.ForeignKey(Orders, on_delete=models.CASCADE)
    direction = models.CharField(max_length=20,related_name="direction",choices=[('COLLECTION','COLLECTION'), 
                                                        ('TRANSFER','TRANSFER')])
    settlement_status = models.CharField(max_length=50,blank=True, null=True,choices=[('YES','YES'), 
                                                                                       ('NO','NO')])
    is_active = models.BooleanField(default=True)

视图.py

from App.models import orders, payments
    #in case if you need objects of order this is for that
    def orderfunc():
        order = Orders.objects.all()
        
    
    def paymentfunc():
        payment = Payment.objects.all()
        # from here you can check for what record you want using conditional operator
#if direction == COLLECTION:
#then do what you need 

推荐阅读