Home > OS >  Django CountryField, query by country
Django CountryField, query by country

Time:11-24

I have a class similar to this:

    class Person(models.Model):
        name = CharField(max_length=255)
        citizenship = CountryField(multiple=True)

In this example a Person can have more than one citizenship.

Person.objects.create(name="Fred Flinstone", citizenship="US, CA")

I want to query for everyone who has a US citizenship, which would return Fred from above. Is there a django-countries way to do this? I suppose I could treat it like a CharField. If I wanted to do something more complex like "is Person a citizen of US or GB", I was hoping there was a nicer way than a complex CharField query.

CodePudding user response:

Try this out:

 Person.objects.filter(citizenship__contains="US")

Also check out the django-countries code, especially tests, if my suggestion is not exactly what you are searching for, I am sure you will find answer there:

Link to tests

  • Related