1

Django ORM で適度に複雑なフィルターを構築しようとしていますが、より効率的に実行できるかどうかわかりません。

私のアプリでは、ユーザーは特定のサイズの靴を検索できます。そのため、ユーザーが 1 つのサイズ (または複数のサイズ) を選択した場合、そのサイズで入手可能なすべての靴を探します。

これが私のモデル構造です。各靴のオブジェクト ( 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このような長いリストでは、クエリが非効率になるのではないかと心配しています。

4

1 に答える 1

0

私はこれを次のようにします:

if query['size']:
    results = results.filter(shoesizeavailable__size__code__in=query['size'])
于 2013-07-15T19:50:35.397 に答える