尝试将sql的左连接转换为django查询集?

jfgube3f  于 2021-07-29  发布在  Java
关注(0)|答案(2)|浏览(262)

这是我的models.py文件

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

    name = models.CharField(max_length=255, null=False)
    firm_name = models.CharField(max_length=255, null=False)
    email = models.EmailField(null=False)
    phone_number = models.CharField(max_length=255, null=False)
    location = models.CharField(max_length=255,null=True)
    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 = (
        ('CR', 'CR'),
        ('DR', 'DR'),
    )

    customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL)
    bill_name = models.CharField(max_length=255, null=False)
    payment_date=models.DateField(auto_now=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)
    description = models.TextField(null=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

我只想访问客户的名称和订单的所有字段,简而言之,我想在django查询集中转换以下sql
选择名称、帐单名称、帐户状态\u customer left join accounts\u order on accounts\u customer.id=accounts\u order.customer\u id where accounts\u order.status=“dr”;

o0lyfsai

o0lyfsai1#

要在订单对象上附加客户名称,可以使用 annotate 带着一个 F 表情。https://docs.djangoproject.com/en/3.0/ref/models/expressions/#using-带注解的f

orders = Order.objects.annotate(
    customer_name=F('customer__name')
).filter(status='DR')

for order in orders:
    print(order.customer_name)

如果您怀疑您将要访问更多的客户属性,您可能需要 select_related (稍微多一些内存,更大的查询)。在django orm中,select\u related和prefetch\u related有什么区别?

orders = Order.objects.select_related('customer').filter(status='DR')

for order in orders:
    print(order.customer.name)
rseugnpd

rseugnpd2#

您可以使用两种方式执行联接操作:第一种:通过使用select\u related,即order.objects,选择\u related('customer');第二种:通过使用filter,即order.objects.filter(status\u iexact=“dr”)

相关问题