开发者

Django/python: loop through a dictionary and add an item to it

Apologies for probably simple question, I've read the docs and still can't get this working.

I'm making a raw SQL query in Django which is long so I won't post it here - suffice it to say that it works and returns results.

I want to loop through my query results and check to see if the bandname is of the format "The [band]" and rewrite it to "[band], The". I'm aware I could do this via SQL but the performance i开发者_高级运维sn't great for a large amount of rows, and I have a function on the band model to sort in this way, but can't use it alongside a raw SQL query.

Here is my code:

m = Media.objects.raw('SELECT blah FROM foo')

for index, item in enumerate(m):
        if item.bandname_alt:
            if item.bandname_alt[:4] == 'The ':
                m[index].bandname_sortable = item.bandname_alt[4:] + ', The'

I know the logic works and finds the right bands, but can't figure out how to add the bandname_sortable field to the dictionary so I can access it inside my views.

Can anyone help me out here?


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 ):
    @property
    def clean_band_name( self ):
        if self.bandname_alt[:4] == 'The ':
            return self.bandname_alt[4:] + ', The'
        else:
            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.

data.sort()


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()?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜