【问题标题】:Simplifying a django ORM query简化 django ORM 查询
【发布时间】:2016-05-13 16:50:18
【问题描述】:

所以这是我的好功能:

def is_serviceable(address):
    """
    Checks if an address can be serviced by an Employee.
    Returns True if address' lat-lng intersects with any of Employees' coverage.
    If it doesn't, but address' locality is listed in world District model,
    returns False and locality name.
    Just returns False if nothing found.

    -- address -- django-address Address object. Address should be geocoded (i.e
    have latitude and longitude fields correctly filled)
    """
    pnt = Point(address.longitude, address.latitude)
    employee_exists = Employee.objects.filter(coverage__mpoly__intersects=pnt).exists()
    district = District.objects.filter(mpoly__intersects=pnt).first()
    if (employee_exists):
        return employee_exists
    elif district:
        return False, district.name
    else:
        return False

为了得到我想要的,我必须执行两个数据库查询,首先是 Employee 表,然后是 District 表。这似乎不是一种可扩展的方法。但是,由于 Employee 的覆盖属性实际上是一个与 District 模型的多对多关系字段:

class Employee(models.Model):
    coverage = models.ManyToManyField(
        District,
        related_name="employees",
        verbose_name=_("assigned districts")
        )

class District(models.Model):
    mpoly = models.MultiPolygonField()

...我很确定有一种方法可以将查询压缩到一个查询集中,或者,如果 Django ORM 不适合此,则可以使用单个 SQL 语句。

不过,我不知道从哪里开始挖掘。有什么想法吗?

编辑:感谢 Django 的注释功能。

【问题讨论】:

    标签: python django


    【解决方案1】:

    Employee 对象可以访问其相关的 District 对象:

    x=Employee.objects.all()[0]
    print x.district_set.all()
    

    【讨论】:

      【解决方案2】:

      您可以对员工人数进行注释,然后根据人数进行过滤

      District.objects.filter(mpoly__intersects=pnt).annotate(emps=Count('employees')).filter(emps__gt=0).first()
      

      您可能还想使用.only('name'),因为这是您在该地区实际使用的所有内容。

      免责声明:这是未经测试的,我不知道这实际上会更快,因为exists 不是很密集

      【讨论】:

      • @khvn - 不用担心,尽情享受吧!您可以通过将elif 更改为if district 来删除检查emp(s) 两次
      • 不错的收获。再次感谢!
      【解决方案3】:

      这是基于Sayse的回答的解决方案:

      pnt = Point(address.longitude, address.latitude)
      district = District.objects.filter(mpoly__intersects=pnt).annotate(emps=Count('employees')).only('name').first()
      if district:
          if district.emps:
              return True
          return False, district.name
      else:
          return False
      

      尚未对其进行分析,但它只是一个查询而不是两个,这是我一直在寻找的。此外,它首先查询 District 表,这意味着对 Employee 表的负载较轻。

      【讨论】:

        猜你喜欢
        • 2019-08-15
        • 2021-06-16
        • 2022-01-08
        • 2020-12-03
        • 2021-10-28
        • 2014-06-13
        • 2021-07-25
        • 1970-01-01
        相关资源
        最近更新 更多