Django ORM 查询

Django ORM making query

我也是 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

您可以使用 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'),
        <b>product_price__lt=OuterRef('product_price')</b>
    ))
)

因此,我们保留 SupplierProducts,其中存在 SupplierProduct,具有不同的 supplier、相同的 product_id 和较低的价格。

之前,先注释,再过滤:

Django-2.2 and older

from django.db.models import Exists, OuterRef, Q

SupplierProduct.objects.<b>annotate(</b>
    <b>has_cheaper=</b>Exists(SupplierProduct.objects.filter(
        ~Q(supplier_id=OuterRef('supplier_id')),
        product_id=OuterRef('product_id'),
        <b>product_price__lt=OuterRef('product_price')</b>
    ))
<b>)</b>.filter(<b>has_cheaper=True</b>)
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)