Django:ORM中跨外键的高效过滤?

Django:ORM中跨外键的高效过滤?,django,django-orm,Django,Django Orm,我正在尝试在Django ORM中构造一个中等复杂的过滤器,我不确定是否可以更有效地完成它 我的应用程序允许用户搜索特定尺寸的鞋子。因此,如果他们选择了一个尺码(或多个尺码),我会寻找该尺码的所有鞋子 这是我的模型结构。每只鞋都有一个对象(shoe),每种尺寸的对象(ShoeSize)(各制造商标准化),以及一个对象(ShoeSizeAvailable),只有在特定尺寸的鞋可用时才会创建该对象 class Shoe(ClothingItem): price = models.FloatFie

我正在尝试在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)

这是最有效的方法吗?我担心查询中的
\u使用这样的长列表可能效率低下

我会这样做:

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