【问题标题】:Django ORM making queryDjango ORM 查询
【发布时间】:2020-12-03 09:24:36
【问题描述】:

我也是djangoSQL 的新手。 我需要列出供应商的产品清单,这些产品有更便宜的同类产品,然后是其他供应商提供的登录(使用相同的product_id)的产品 要求:Django=2.2 PostgreSQL=9.6 通过django-ORM 告诉我如何执行此操作,以及仅使用 SQL 语言应该是什么代码 这是模型。

Models.py
class Product(models.Model):
    name = models.CharField('product name', max_length=50)
    product = models.CharField('vendor code', default=None, max_length=50, unique=True)

class Supplier(models.Model):
    name = models.CharField('Supplier name', default='', max_length=50)

Class SupplierProduct(models.Model): 
    supplier = models.ForeignKey(Supplier, default=None, on_delete=models.CASCADE)
    product = models.ForeignKey(Product, default=None, on_delete=models.CASCADE)
    product_price = models.DecimalField('Price', default=None, max_digits=11, decimal_places=2)
    availability = models.BooleanField(default=False)

Views.py
def foo(request):
    user = request.user

【问题讨论】:

  • 感谢大家。我的问题变了。我已经用 SQL 解决了。以及它应该如何在 ORM 中? SELECT * FROM (( SELECT * FROM SupplierProduct a WHERE a.supplier_id = 2 ) 作为我的加入 (SELECT * FROM SupplierProduct b WHERE b.supplier_id 2) 作为其他人在 my.product_id = others.product_id ) WHERE my.product_price > others.product_price AND my.availability = true AND others.availability = true

标签: sql django-orm postgresql-9.6


【解决方案1】:
SupplierProduct.objects.annotate(
    has_cheaper=Exists(SupplierProduct.objects.filter(
        Q(supplier__name=user),
        ~Q(supplier_id=OuterRef('supplier_id')),
        product_id=OuterRef('product_id'),
        product_price__gt = OuterRef('product_price')
        )
    )
).filter(availability=True, has_cheaper=True)

【讨论】:

    【解决方案2】:

    您可以使用Exists subquery [Django-doc]

    from django.db.models import Exists, OuterRef, Q
    
    SupplierProduct.objects.filter(
        Exists(SupplierProduct.objects.filter(
            ~Q(supplier_id=OuterRef('supplier_id')),
            product_id=OuterRef('product_id'),
            product_price__lt=OuterRef('product_price')
        ))
    )

    因此,我们保留SupplierProducts,其中存在一个SupplierProduct,具有不同的supplier、相同的product_id,并且价格更低。

    之前,先注解,再过滤:

    Django-2.2 and older
    
    from django.db.models import Exists, OuterRef, Q
    
    SupplierProduct.objects.annotate(
        has_cheaper=Exists(SupplierProduct.objects.filter(
            ~Q(supplier_id=OuterRef('supplier_id')),
            product_id=OuterRef('product_id'),
            product_price__lt=OuterRef('product_price')
        ))
    ).filter(has_cheaper=True)

    【讨论】:

    • 感谢您的回答!!!但它不适用于 django 2.2,它适用于 django>=3。
    • @Rash-77:那你首先需要注释,见编辑。
    猜你喜欢
    • 2014-06-13
    • 2021-07-25
    • 1970-01-01
    • 2011-06-15
    • 2018-05-21
    • 2020-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多