2016-01-26 92 views
5

私のホームページに検索フィールドを含めることを試みています。これは、モジュールフィールドの一部で機能します。私の問題は、私がForeignKeyフィールドを使用するときです(私が間違っていれば私を修正してください)。関連フィールド無効な参照が取得されました:icontains

models.py

class Location(models.Model): 
    user = models.ForeignKey(User, on_delete=models.CASCADE) 
    my_location = models.CharField(max_length=120, choices=LOCATION_CHOICES) 
    update_date = models.DateField(auto_now=True, null=True) 

    def __str__(self): 
     return self.my_location 


class UserProfile(models.Model): 

    user = models.ForeignKey(User) 
    # The additional attributes we wish to include. 
    user_base = models.CharField(max_length=120, choices=LOCATION_CHOICES) 
    user_position = models.CharField(max_length=120) 
    user_phone = models.PositiveIntegerField() 

    def __unicode__(self): 
     return self.user.username 

views.py

def search_by_location(request): 
    if 'q' in request.GET and request.GET['q']: 
     q = request.GET['q'] 
     locations = Location.objects.filter(my_location__icontains=q).order_by('-update_date') 
    else: 
     locations = Location.objects.order_by('-update_date') 
context = {'locations': locations} 
return render(request, 'index.html', context) 

私の問題は、私が代わりにmy_locationのフィルタクエリ内userを使用する場合、私はエラーを受け取ります:

Related Field got invalid lookup: icontains

トラブルシューティングの方法や私が読むことができるドキュメントに関するアドバイスをお願いします。

答えて

15

テキストフィールドでicontainsルックアップを使用できます。 userは関連する(整数)フィールドです。 userの代わりにuser__usernameを使用してください。

locations = Location.objects.filter(user__username__icontains=q) 
+0

ありがとうございました。 3分が過ぎれば、私は好きな答えとしてそれを入れます:P。 –

関連する問題