Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
118 views
in Technique[技术] by (71.8m points)

python - Filter objects in a queryset by a boolean condition

I would like to filter objects in a Queryset according to a Boolean condition and can’t figure out the best way to do it. At the moment I have two models:

class Language(models.Model):
    langcode = models.CharField(max_length=3, unique=True)
    Translated = models.BooleanField(default=False)

class Countries(models.Model):
    countrycode = models.CharField(max_length=3, unique=True)
    spoken_languages = models.ManyToManyField(Language)
    Continent = models.CharField(max_length=50)

This represents a table of unique languages and a table of unique countries. Many countries speak many different languages but not every language has been translated yet.

What I would like now is a Countries queryset where only translated languages appear in the spoken language section. My ideas were to make a Countries model property “translated_languages” that updates automatically when a languages Translated is turned True. But I can't figure out how to make it behave like I want it too (auto update when language gets translated etc.). Second attempt was to filter it on a view level but here I failed again because I couldn’t figure out how to filter it for each Country individually and store it. Then I tried it on a template level but filter doesn’t work there.

In the end, I would like to use the object in two template for loops:

{% for country in Countries %}
    {% for language in country.spoken_languages.all %}
        {{ language }}

So what would be your opinion on this? What’s the best approach (template, view, model) and how could it be done? Please let me know if it’s still unclear and thanks in advance

question from:https://stackoverflow.com/questions/65918935/filter-objects-in-a-queryset-by-a-boolean-condition

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just add a method in you Countries model (Note it is bad practice to name models in the plural sense Country would be a better name):

class Countries(models.Model):
    countrycode = models.CharField(max_length=3, unique=True)
    spoken_languages = models.ManyToManyField(Language)
    Continent = models.CharField(max_length=50)
    
    def translated_spoken_languages(self):
        return self.spoken_languages.filter(Translated=True)

Now in your templates:

{% for country in Countries %}
    {% for language in country.translated_spoken_languages %}
        {{ language }}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...