Note that there are some explanatory texts on larger screens.

plurals
  1. POGeoDjango: Sort by country of the geolocation
    primarykey
    data
    text
    <p>Hi Stackoverflow people, </p> <p>I have a model which contains projects with the corresponding geolocation:</p> <pre><code>class Project(models.Model): name = models.CharField(_('Project Name'), max_length=100, null=True, blank=True) geolocation = models.PointField(_('Project Location')) ... </code></pre> <p>In addition, another model is representing a shapefile with the country borders:</p> <pre><code>class WorldBorder(models.Model): name = models.CharField(max_length=50) mpoly = models.MultiPolygonField() objects = models.GeoManager() class Meta: ordering = ('name',) def __unicode__(self): return self.name </code></pre> <p><strong>How can I do a query on Project and order the results by the country name of the geolocation?</strong> A query like </p> <blockquote> <p>d = Project.objects.all().order_by(geolocation__name)</p> </blockquote> <p>does not work since geolocation is not a Foreignkey. <strong>Do I really have loop through all projects and determine the country manually like in my example below?</strong></p> <pre><code>projects = Project.objects.all() result = [] for project in projects country = WorldBorder.objects.filter(mpoly__contains = project.geolocation) foo = [project.name, country] result.append(foo) # now sort the list according to the country result = sorted(result, key=itemgetter(1)) </code></pre> <p><strong>There should be a more professional and elegant solution? Any suggestions from the experienced Python people?</strong> Can I use joins for that purpose?</p> <p>Thank you for your suggestions!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload