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
このような長いリストでは、クエリが非効率になるのではないかと心配しています。