Django:在ForeignKeys的ORM中高效过滤? [英] Django: efficient filtering in the ORM across ForeignKeys?

查看:148
本文介绍了Django:在ForeignKeys的ORM中高效过滤?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Django ORM中构建一个适度复杂的过滤器,我不知道我能否更有效地执行。

I'm trying to construct a moderately complex filter in the Django ORM, and I'm not sure if I could do it more efficiently.

我的应用允许用户搜索特定尺寸的鞋子。所以如果他们选择一个尺寸(或多个尺寸),我寻找所有可用的这种尺寸的鞋子。

My app lets users search for shoes in a particular size. So if they select a size (or multiple sizes), I look for all the shoes available in that size.

这是我的模型结构。每个鞋子( Shoe )的对象,每个尺寸的对象( ShoeSize )(制造商标准化)以及仅在特定尺寸可用的特定鞋子时才能创建的对象( ShoeSizeAvailable )。

This is my model structure. There's an object for each shoe (Shoe), an object for each size (ShoeSize) (standardised across manufacturers), and an object (ShoeSizeAvailable) that only gets created if a particular shoe is available in a particular size.

class Shoe(ClothingItem):
  price = models.FloatField(null=True,blank=True,db_index=True) ... 

class ShoeSize(models.Model):
  code = models.CharField(max_length=8) ...

class ShoeSizeAvailable(models.Model):
  shoe = models.ForeignKey(Shoe)
  size = models.ForeignKey(ShoeSize)

这是我当前的过滤方式:

And this is how I currently do the filtering:

kwargs = {}
args = ()
if query['price_from']: 
  kwargs['price__gte'] = float(query['price_from'][0])
# Lots of other filters here... 
results = Shoe.objects.filter(*args, **kwargs)

if query['size']: 
    # The query is a list like [6, 6.5]
    # Get all potential ShoeSizeAvailable matches. 
    sizes = ShoeSizeAvailable.objects.filter(size__code__in=query['size'])
    # Get only the ones that apply to the current shoe. 
    shoe_ids = sizes.values_list('shoe', flat=True)
    # Filter the existing shoe results for these values.  
    results = results.filter(id__in=shoe_ids)

这是最有效的方式吗?我担心查询中的 __可能对这些长列表可能无效。

Is this the most efficient way? I'm concerned that __in queries might be inefficient with long lists like these.

推荐答案

我将这样做:

if query['size']:
    results = results.filter(shoesizeavailable__size__code__in=query['size'])

这篇关于Django:在ForeignKeys的ORM中高效过滤?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆