title: geodjango foreignkey by distance
body: <p>i'm struggling with complicated Django queries, mainly because I try to do something that might be complicated.</p>
  
  <p>Basically, I got this :</p>
  
  <p><em>models.py :</em></p>
  
  <pre><code>from django.contrib.gis.db import models
  
  class Show(models.Model):
    name = models.CharField()
  
  class Venue(models.Models):
    name = models.CharField()
    coords = models.PointField()
    objects = models.GeoManager()
  
  class Representation(models.Model):
    datetime = models.DateTimeField()
    venue = models.ForeignKey(Venue)
    show = models.ForeignKey(Show)
  </code></pre>
  
  <p>Now, what I want to do is, get 5 incoming shows that are close to user (user.geoloc is a Point). One of the complicated thing is that some of my users may live in area where there are no venue, and, my solution is just, if there is not enough shows close to them, to search in a bigger area.</p>
  
  <p><em>view.py :</em></p>
  
  <pre><code>from django.contrib.gis.measure import D
  
  DISTANCE_CLOSE = 1000 #arbitrary number
  
  ## this thing is not working, because it's not how it should be done
  ## but the logic is clearer in this
  def get_nearest_shows_not_working(request): 
    list_shows = {}
    while len(list_shows&lt;5)
      list_shows = Show.representation_set.filter(venue__coords__distance_lte=(user.geoloc, D(m=DISTANCE_CLOSE))).order_by('datetime'):[5]
      DISTANCE_CLOSE = int(DISTANCE_CLOSE*1.2)
    return render(request, 'template.html', locals())
  
  def get_nearest_shows_ducktape(request):
    list_shows = set()
    while len(list_show) &lt; 5:
      list_rep = Representation.objects.filter(venue__coords__distance_lte=(user.geoloc, D(m=DISTANCE_CLOSE))).order_by('datetime')
      for rep in list_rep:
        list_shows.add(rep.show)
      DISTANCE_CLOSE = int(DISTANCE_CLOSE*1.2)
    list_shows = list_shows[:5]
    return render(request, 'template.html', locals())
  </code></pre>
  
  <p>What am I missing ? in Python, there shoud be one and only right way to do something, and here, I'm just messing with complicated things, this looks unpythonic to me.      </p>