[Answered ]-Django/python: loop through a dictionary and add an item to it


First, avoid raw SQL queries. They’re rarely necessary. That’s a separate question, however.

You have two ways to touch up your results.

In the model. If you can find a way to avoid raw SQL, you can easily add a property to your model to handle this.

class Media( models.Model ):
    def clean_band_name( self ):
        if self.bandname_alt[:4] == 'The ':
            return self.bandname_alt[4:] + ', The'
            return self.bandname_alt

You can use sorted( list(results), key=lambda x: x.clean_band_name() )

In the View. Build simple list of tuples or list of named tuples with your expanded results.

data = [ (cleanup(item.bandname_alt), item) for item in m ]

Since data is a simple sequence it can be sorted by the first element in each tuple.



I’m assuming as you mentioned that you have a good reason for the raw query. That’s fine, perhaps you can instantiate an object of Media for each interation, load in your PK and set your values and run a .save()?

Leave a comment