Django:在ForeignKeys的ORM中有效过滤?

时间:2013-07-15 17:19:13

标签: django django-orm

我正在尝试在Django ORM中构建一个中等复杂的过滤器,我不确定我是否可以更高效地完成它。

我的应用可让用户搜索特定尺寸的鞋子。因此,如果他们选择尺码(或多种尺码),我会寻找所有尺码的鞋子。

这是我的模型结构。每个鞋子都有一个对象(Shoe),每个尺寸的对象(ShoeSize)(制造商标准化)和一个对象(ShoeSizeAvailable)只有在特定鞋子时才会被创建有特定尺寸可供选择。

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)

这就是我目前的过滤方式:

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)

这是最有效的方式吗?我担心__in查询对于像这样的长列表可能效率低下。

1 个答案:

答案 0 :(得分:0)

我会这样做:

if query['size']:
    results = results.filter(shoesizeavailable__size__code__in=query['size'])
相关问题