0

I have a queryset of countries where some of them start with non english characters like "Þ" and "Í", when using order_by they are just shown at the end instead of being sorted properly.

This is the result:

>>> from someapp.models import Country
>>> countries = Country.objects.all().order_by("country")
>>> countries
<QuerySet [<Country: Bandaríkin>, <Country: Bretland>, <Country: Danmörk>, <Country: Kanada>, <Country: Noregur>, <Country: Svíþjóð>, <Country: Ísland>, <Country: Þýskaland>]>

How would I use order_by with a non english alphabet?

Here is the model:

class Country(models.Model):
    country = models.CharField(max_length=100, unique=True)

    def __str__(self):
        return "%s" % (self.country)

    class Meta:
        ordering = ['country']
DevB2F
  • 4,674
  • 4
  • 36
  • 60
  • 3
    This is determined by your database's `collation` field, which Django doesn't set - tables will be created using whatever the database is set to use as its default. You can change this, but the details will depend on what database you're using. See for instance this discussion: https://docs.djangoproject.com/en/2.2/ref/databases/#collation-settings - which links to the MySQL docs. – Peter DeGlopper Aug 24 '19 at 01:56
  • how would this be done for Postgres? – DevB2F Aug 24 '19 at 05:08
  • 1
    I'm not very knowledgeable about Postgres, unfortunately. Checking the docs and https://stackoverflow.com/questions/19420925/change-database-collation-ctype-in-postgresql I see that a) you can't change it for an already-created table, but b) you can dump and reimport the data after creating a new database with the desired collation as the default. If you can't drop the whole database (say because it's shared, or because there's enough data that exporting and reimporting would be too slow) I think you can also do it with an edit to the `create table` SQL and then drop/recreate the table. – Peter DeGlopper Aug 24 '19 at 14:06
  • (I'm not good enough with either Postgres or the current state of Django migrations to give a response I feel good enough to turn into an answer, possibly someone else will. Or will turn up an existing dupe.) – Peter DeGlopper Aug 24 '19 at 14:08

0 Answers0