I’m a PHP guy on my first day in Python-land, trying to convert a php site to python (learning experience), and I’m hurting for advice. I never thought it would be so hard to use multi-dimensional arrays or dictionaries as you pythoners call them.
So I can create multi-dimensional arrays using this, but i can’t loop it in a django template. this doesnt work but i imagine i cant loop through it if i could get it to work.
{% for key,val in dictionary.items %}
only works for actual dictionaries it seems, not the custon multi-dimensional dictionary classes.
I’m creating my dictionary from a sql query:
vid[ video[ 7 ] ][ 'cat_short_name' ] = video[ 2 ]
vid[ video[ 7 ] ][ 'cat_name' ] = video[ 1 ]
vid[ video[ 7 ] ][ 'cat_id' ] = video[ 7 ]
vid[ video[ 7 ] ][ 'companies' ][ video[ 14 ] ][ 'comp_short_name' ] = video[ 5 ]
vid[ video[ 7 ] ][ 'companies' ][ video[ 14 ] ][ 'comp_name' ] = video[ 4 ]
vid[ video[ 7 ] ][ 'companies' ][ video[ 14 ] ][ 'comp_website' ] = video[ 6 ]
vid[ video[ 7 ] ][ 'companies' ][ video[ 14 ] ][ 'videos' ][ video[ 8 ] ][ 'top_video' ] = 0
vid[ video[ 7 ] ][ 'companies' ][ video[ 14 ] ][ 'videos' ][ video[ 8 ] ][ 'vid_id' ] = video[ 8 ]
vid[ video[ 7 ] ][ 'companies' ][ video[ 14 ] ][ 'videos' ][ video[ 8 ] ][ 'vid_name' ] = video[ 9 ]
vid[ video[ 7 ] ][ 'companies' ][ video[ 14 ] ][ 'videos' ][ video[ 8 ] ][ 'vid_url' ] = video[ 10 ]
I basically need to get all companies in a certain category and then get all videos in that company so i can nest them easily in my template. This is how i did it in php, creating one huge deep array. Trying to duplicate in Python has proven difficult.
I thought maybe i could do with the backwards lookups in django using set_MODEL but i couldn’t figure that out either.
Any help on how to accomplish my goal would be appreciated. I hope my question is clear
EDIT:
When im done looping in my template it looks like this…
<h1>Category</h1>
<h2>Company</h2>
<ul>
<li>video</li>
</ul>
<h2>Company</h2>
<ul>
<li>video</li>
<li>video</li>
</ul>
<h1>Category</h1>
<h2>Company</h2>
<ul>
<li>video</li>
</ul>
<h2>Company</h2>
<ul>
<li>video</li>
<li>video</li>
</ul>
You should be using the built in ORM instead of using your own queries (at least for something simple like this), makes things much easier (assuming you’ve also built your models in your models.py file)
In your view:
In your template:
I haven’t tested it but it should work. Compare this code to what you would have to write if you weren’t using ORM, in either PHP or Python.
take a look at the django docs for more info, I’d recommend taking a few hours and doing the tutorial.
Update: modified the code to use “_set.all”