代码之家  ›  专栏  ›  技术社区  ›  blue_note

sqlachemy:按关系过滤(比如django orm)?

  •  1
  • blue_note  · 技术社区  · 6 年前

    class Product(models.Model):
        product_id = models.IntegerField(primary_key=True)
        color = models.TextField()
    
    class Sale(models.Model):
        sale_id = models.IntegerField(primary_key=True)
        timestamp = models.DateTimeField()
        product = models.ForeignKey(Product, on_delete=models.CASCADE)
    

    你能做到的

    Sale.objects.filter(product__color__in=['red', 'blue'])
    

    甚至相反

    Product.objects.filter(sale__timestamp__gt=datetime.now())
    

    没有显式联接 s??

    1 回复  |  直到 6 年前
        1
  •  1
  •   Ilja Everilä    6 年前

    你可以用 any() and has()

    session.query(Product).filter(Product.sales.any(Sale.timestamp > datetime.now()))
    

    session.query(Sale).filter(Sale.product.has(Product.color.in_(['red', 'blue'])))
    

    不幸的是,与使用显式联接相比,在某些DBMS上EXISTS子查询表达式的性能可能较差。