Ich versuche, ein Suchfeld in meine Homepage aufzunehmen. Es funktioniert für einige der Modulfelder. Mein Problem ist, wenn ich ein ForeignKey-Feld verwende (korrigiert mich bitte, wenn ich falsch liege).Verwandte Feld wurde ungültige Suche: 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)
Mein Problem ist, wenn ich user
innerhalb der Filterabfrage statt my_location
verwenden erhalte ich die Fehlermeldung:
Related Field got invalid lookup: icontains
Bitte geben Sie Ratschläge zur Fehlerbehebung oder Dokumentation, die ich lesen kann.
Es hat funktioniert. Vielen Dank. Ich werde es als eine Lieblingsantwort setzen, sobald die 3 Minuten vergehen: P. –