2017-07-05 8 views
1

データベースで全文検索を使用し、検索する列を選択したいと考えています。すべての列(果物、野菜、乳製品)を含む食品モデルにsearch_vectorフィールドが1つしかない場合、特定の列(果物のみのようなもの)を検索する方法はありますか?私はすべての列を検索したいので、すべての検索ベクトルを組み合わせたのです。全文検索django postgresの組み込み全文検索を使用して特定の列を検索する

私はDjangoの1.11に

を使用していますここに私のモデルです:

class Food(models.Model): 
    fruits = models.CharField(max_length=50) 
    vegetables = models.CharField(max_length=50) 
    dairy = models.CharField(max_length=50) 
    search_vector = SearchVectorField(null=True) 

は、ここで私はベクトルを保存する方法は次のとおりです。

vector= SearchVector('fruits', weight='A') + \ 
     SearchVector('vegetables', weight='B') + \ 
     SearchVector('dairy', weight='C') + \ 
Food.objects.annotate(document=vector).values_list('document', flat=True) 


for f in Food.objects.annotate(document=vector): 
    f.search_vector = f.document 
    f.save(update_fields=['search_vector']) 

は、ここで私は、検索方法は次のとおりです。

search_result = Food.objects\ 
    .annotate(rank=SearchRank(F('search_vector'), "apple"))\ 
    .filter(search_vector="apple")\ 

簡単なwはありますか?私が設定したsearch_vectorの果物の列だけを検索するか、各列ごとに個別の検索ベクトルを設定する必要がありますか?

答えて

1

は単に

result = Food.objects.filter(**{fruits + "__search": "apple"}) 
をフィルタリングすることにより、これを達成することができました