'Django How to search if field is ForeignKey?
Good day SO:
So I have something like the following:
class Nationalities(models.Model):
country_name = models.CharField(...)
class Profile(models.Model):
name = models.CharField(...)
name_kana = models.CharField(...)
name_kanji = models.CharField(...)
nationality = models.ForeignKey(Nationality...on_delete=models.CASCADE)
What I tried:
finalqs = ""
nameqs = ""
countryqs = ""
if request.POST['search_name'] != '':
nameqs = Q(name_kana__icontains=request.POST['search_name']) | .....
if request.POST['search_country'] != '':
countryObj = Nationalities.objects.filter(country_name__icontains=request.POST['search_country'])
countryqs = Q(nationality__icontains=countryObj)
if nameqs != "" :
if finalqs != "":
finalqs += ", " + nameqs
else:
finalqs = nameqs
if countryqs != "" :
if finalqs != "":
finalqs += ", " + countryqs
else:
finalqs = countryqs
if finalqs != "":
hrItems = Profile.objects.filter(finalqs)
else:
hrItems = Profile.objects.all()
Right now, if I only search for names, I get the result that I want but if I include the country, it gives error message
Related Field got invalid lookup: contains
Sorry if I confuse you on my question. I am still trying to learn about django. What I want to do is do a search function. As of now, I can search by name using the contains/icontains. However on the same form, if I want to search nationality(which in my model was created by ForeignKey) it returns the said error. Maybe on how I wrote the code or something
Solution 1:[1]
If I understand correctly you just want to fetch the correct records by filtering the args from the request. while your code can work with some edits, the right way to do it is via Django Model forms
so in your case:
class ProfileForm(ModelForm):
class Meta:
model = Profile
fields = ['name_kanji', 'name_kana', 'name', 'nationality']
On the view it should be easy as:
// this validates that all the values pass (name is a string, nationality is an id that exists )
p = ProfileForm(request.POST, instance=a)
//this saves the data
new_profile = p.save()
the only important thing otherwise that you need to keep track of is seeing that you're sending the correct values and names to the server
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | elad silver |