简体   繁体   中英

django filter queryset based on __str__ of model

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!

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM