Home > database >  Django complex filter with two tables
Django complex filter with two tables

Time:09-28

I am in need of some help. I am struggling to figure this out. I have two models

class Orders(models.Model):
    order_id = models.CharField(primary_key=True, max_length=255)
    channel = models.CharField(max_length=255, blank=True, null=True)
    
    def __str__(self):
        return str(self.order_id)

    class Meta:
        managed = False
        db_table = 'orders'

class OrderPaymentMethods(models.Model):
    id = models.CharField(primary_key=True, max_length=255)
    payment_type = models.CharField(max_length=75, blank=True, null=True)
    fk_order = models.ForeignKey('Orders', models.DO_NOTHING, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'order_payment_methods'

My goal is to count the number of orders that have a OrderPaymentMethods specific payment_type Example:

orders = Orders.object.filter(Q(channel="Green_House"))
method_money = orders.filter(payment_methods = "credit").count()

How can I get the count based on the orders that were filtered?
Thank You

CodePudding user response:

You don't need Q nor separating such query. You need to use relation lookup:

Orders.object.filter(channel="Green_House", orderpaymentmethods_set__payment_type="credit").count()
  • Related