[Answered ]-Better way to query this Django Model


You can do it with the model query api, but if you already have the raw sql written that’s going to be more efficient in the long term if you have to scale to enormous heights.

Pro of raw SQL: More efficiently hit the database.
Pro of query api: Non SQL django people will be able to maintian and extend your code in the future.

I’ve been interacting with databases via django’s orm so long that I’m struggling to figure out what your query even means.

#I think this gets what you want
positions = Position.objects.filter(directorio__activated=True).order_by('category__n_catgory', 'website_position')
for position in positions:
    print position.category.n_category, position.website_position, position.directorio.website_name, position.website.website_url, position.website.activated

The key to migrating from SQL to django’s ORM is starting to think in terms of the primary object(s) you want, then walking the relationships to get the related data. All data related to an object is available to you via object/dot notation, and thanks to the django ORM’s laziness, most of it isn’t retrieved until you ask for it.

The above code gets every position by category, then walks the relationships to get the other data. Another version of the code might get every active website then show its categories and positions:

websites = Directorio.objects.filter(activated=True).order_by('website_name')
for website in websites:
    print website.website_name, website.website_url, website.activated
    for position in website.position_set.all().order_by('category__n_category'):
        print " -- ", position.category.n_category, position.website_position

Leave a comment