简体   繁体   中英

Convert SQL query set into Django Model Query-set?

I want to convert the following query of SQL into Django Query-set:-

select sum(amount) from accounts_order where status='Pending' and customer_id=1;

here is my models.py file

from django.db import models

Create your models here.

class Customer(models.Model):
    """All Customers details goes here"""

    name = models.CharField(max_length=255, null=False)
    email = models.EmailField(null=False)
    phone_number = models.CharField(max_length=255, null=False)
    date_created = models.DateTimeField(auto_now_add=True)

    class Meta:
        """Meta definition for Customer."""

        verbose_name = 'Customer'
        verbose_name_plural = 'Customers'

    def __str__(self):
        """Unicode representation of Customer."""
        return self.name


class Order(models.Model):
    """All order details goes here.It has OneToMany relationship with  Customer"""
    STATUS = (
        ('Pending', 'Pending'),
        ('Done', 'Done'),
    )

    customer = models.ForeignKey(
        Customer, null=True, on_delete=models.SET_NULL)
    bill_name = models.CharField(max_length=255, null=False)
    status = models.CharField(max_length=255, choices=STATUS, null=False)
    amount = models.FloatField(max_length=255, null=False)
    date_created = models.DateTimeField(auto_now_add=True)

    class Meta:
        """Meta definition for Order."""

        verbose_name = 'Order'
        verbose_name_plural = 'Orders'

    def __str__(self):
        """Unicode representation of Order."""
        return self.bill_name

You can use a .aggregate(…) [Django-doc] here:

from django.db.models import Sum

Order.objects.filter(
    status='Pending', customer_id=1
).aggregate()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM