Reputation: 18158
I have the following model:
class Subspecies(models.Model):
species = models.ForeignKey(Species)
subspecies = models.CharField(max_length=100)
def __str__(self):
return self.species.species_english+" "+self.species.species+" "+self.subspecies
def __unicode__(self):
return self.species.species_english+" "+self.species.species+" "+self.subspecies
Notice that the ForeignKey field, species
is used in the __str__
and __unicode__
methods. I had made this filter query:
l = list(Subspecies.objects.filter(subspecies__contains=request.GET.get('term')).order_by('subspecies')[:10])
This is almost what I want, except not quite. What I really want is a filter that checks if the __str__
representation of the object contains some group of characters, instead of just checking the subspecies
field. Instead of subspecies__contains=...
it would be something like __str____contains=...
but of course that doesn't work.
Is this possible? IF so how would I make this query?
Thanks!
Upvotes: 5
Views: 8780
Reputation: 4371
The best approach I found here is to mark your target with a quotation (' '). then slice the string and filter based on it .. here is how it goes in your case
class Subspecies(models.Model):
species = models.ForeignKey(Species)
subspecies = models.CharField(max_length=100)
def __str__(self):
return self.species.species_english+" "+self.species.species+" "+" 'str(self.subspecies)'"
def __unicode__(self):
return self.species.species_english+" "+self.species.species+" "+" 'str(self.subspecies)'"
As you see your subspecies
part now are between ' '
Then you do the next to filter based on it :
sub_input = request.GET.get('term')
sub = sub_input .split("'")[1::2] #not sure how did [1::2] works but it is the only way that worked for me
l = Subspecies.objects.filter(subspecie=sub[0]) #used indexing as split gives you result as a list
Upvotes: 0
Reputation: 4668
Filter generates a query to be executed in DB.
__str__
is run in Python interpreter. You can't call it from DB.
SO the short answer is "no, you can't". You have to filter it manually, using filter
built-in function, for example.
Upvotes: 7