[Answered ]-Get query result as a tuple to make substitution

1👍

I use something similar. What you need to do is to decorate/wrap the row with a __getitem__ and then use %(colname)s rather than %s in the template’s values.

class Wrapper(object):
    def __init__(self,o):
        self.o = o
    def __getitem__(self,key):
        try:
            return getattr(self.o, key)
        except AttributeError:
            raise KeyError, key

Then, using the django shell (my model has one column, tagtype)

python manage.py shell
>>> from wrapper import Wrapper
>>> from pssystem.models import MetaTag
>>> o = MetaTag.objects.all()[0]
>>> w = Wrapper(o)
>>> "insert into sourcetable (attr1,attr2,attr3) values ('%(tagtype)s','%(tagtype)s, '%(tagtype)s)" % w
u"insert into sourcetable (attr1,attr2,attr3) values ('PROFILE','PROFILE, 'PROFILE)"

You can get fancier than that (and you definitely should if the source object contains untrusted, user-entered, content), but this works fine.

Notice that you need to add quotes around the substitutions if those are character variables. Dates might also be fun too!

Hmmm, sorry, just noticed that your source rows are coming from a straight select rather than a fetch from a Django model. The Django tag confused me — there is very little Django in your question. Well then, it still works, but you first need to do something with the cursor’s result rows.

Something like this does the trick:

def fmtRow(cursor, row):
    di = dict()
    for i, col in enumerate(cursor.description):
        di[col] = row[i]
    return di

and then you can dispense with the Wrapper, because your row is changed to a dictionary already.

This is a very naive implementation, not suitable for high volumes, but it works.

1👍

You can use kwargs to update querysets dynamically.

kwargs = {'name': "Jenny", 'color': "Blue"}
print People.objects.filter(**kwargs)

I’m not sure this helps with the dynamically named table though. Maybe something like this would help: http://dynamic-models.readthedocs.org/en/latest/ (it’s where that kwarg example came from).

Leave a comment