1

I'm using django-countries to set a country in my django model:

# models.py
from django_countries.fields import CountryField

class MyModel(models.Model):
    title = models.CharField(max_length=255, blank=True)
    country = CountryField()

I would like a have a queryset ordered by country.name, but apparently the following queryset:

MyModel.objects.live().order_by('country__name')

does not work:

Cannot resolve keyword 'name' into field. Join on 'country' not permitted.

Further it is - apparently - not possible to use the model Meta option ordering.

I could get it ordered in the template by: {% for item in items.all|dictsort:"country.name" %} but would prefer to get this done in the queryset.

Did you, dear internet, are aware of a way to get this queryset orderd by country.name?

tombreit
  • 1,199
  • 8
  • 27
  • Can you post the relevant parts of `MyModel`, is `country` a `ForeignKey`? – Willem Van Onsem Jun 12 '18 at 18:34
  • It looks to me, that `Country` is not a model, hence querying in such way, is - at least not by default - enabled. – Willem Van Onsem Jun 12 '18 at 18:35
  • It is in fact - behind the curtains - a simple `CharField`, that stores country codes, so this makes it impossible to do this directly. – Willem Van Onsem Jun 12 '18 at 18:36
  • Hm, that's what I feared ;-) Are there no ways around this - like annotating the queryset with the ``country.name``? – tombreit Jun 12 '18 at 19:46
  • not unless you make some sort of model yourself that maps these two-char elements to country names. The point is that the database only stores the two-char code, like `'us'`, `uk'`, `'de'`. So it does not know what the names of the countries are at all. For the database, those are only 2-char strings. – Willem Van Onsem Jun 12 '18 at 19:48
  • Ok, that would be overkill in my case, as I successfully sorted this in the template via ``dictsort``. – tombreit Jun 12 '18 at 20:33

0 Answers0