Jonathan Buchanan wrote: >> To understand the problem, assume I have a model consisting of Country >> and SoccerTeam. >> >> The SoccerTeam has a country = models.ForeignKey(Country). >> >> Say, I need to find the countries having one or more related soccer >> teams. I was not able to come up with a solution using the ORM... >> >> ...Do I really need to use custom SQL here, or does the django ORM provide >> the means to solve this problem? > > You could use QuerySet's "extra" method to add the custom SQL > required, which might be something like the following in this case > (you'd need to replace "appname" with the name of the application the > models belong to, of course): > > Country.objects.all().extra( > where=['(SELECT COUNT(*) FROM appname_soccerteam WHERE > appname_soccerteam.country_id = appname_country.id) > 0'] > )
Great idea! I did not think about the 'extra' method. Works perfectly. Gave me a speedup factor of about 250k :) Thanks, -- Christian Joergensen | Linux, programming or web consultancy http://www.razor.dk | Visit us at: http://www.gmta.info
signature.asc
Description: OpenPGP digital signature