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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…