Hi Stackoverflow people,
I am confused with m2m queries in Django. I have a model RadioStations which lists radio stations around a continent (simply name and the available country) and has the following declaration:
class Station(models.Model):
name = models.CharField(_('Station Name'), max_length=255
reference = models.URLField(_('Link'), blank=True, verify_exists=True)
country = models.ManyToManyField(WorldBorder)
The class WorldBorder follows the GeoDjango example here.
Now I would like to search for all stations in the US.
If I use:
s = Station.objects.filter(country__name__contains = "United States")
I get all stations in the US. However, if I now search with a user location, e.g.
pnt = fromstr('POINT(-96.876369 29.905320)', srid=4326)
s = Station.objects.filter(country__mpoly__contains = pnt)
the result of the query is empty (even so the point is located in the U.S.
Is that related to the way of doing a m2m query? Why would the results of the query being empty? Is there a different way of addressing the m2m relationship?
Thank you for your suggestions!
The solution to the question is the follows:
Instead of going from
StationstoWorldBorder, I ended up going the other way.Django allows the reversed look up through the
attribute_set.all()method.The solution is to look up which country contains the
Pointwithand then look up all
Stationswhich contain the country withNote that the
set.all()requires a get query, and not a filter query.More background on the set.all() method can be found here.