getattr in pony generators orm

3

I have the following problem (whose answer I fear is that it does not support it). I have verified that this sentence runs without problems:

res = tuple(Cliente.select(lambda c: c.nombre == "Pepe"))

But my problem is that name is inside a variable, so I tried the following to try:

res = tuple(Cliente.select(lambda c: getattr(c, "nombre") == "Pepe"))

This, on the other hand, returns an error TypeError: getattr(c, 'nombre') . I do not think that there is an error with such a concept, so I think that simply, pony-orm does not support it. Do you know anything?

    
asked by José Miguel SA 02.03.2016 в 09:04
source

1 answer

3

Currently Pony ORM does not allow the use of getattr . We want to add this function in the future. This is a bit non-trivial, because Pony ORM is translated to SQL generator only once, and then the result of the translation is cached. When using getattr , different name of the attribute produces different queries. So we'll have to add the attribute name in a cache key. At this time you can solve the problem by using textual query:

attr = 'nombre'
res = tuple(Cliente.select('lambda c: c.%s == "Pepe"' % attr))

The textual query is working in the same way as a regular query, you can pass parameters to it:

attr = 'nombre'
x = 'Pepe'
res = tuple(Cliente.select('lambda c: c.%s == x' % attr))

You need to be careful not to replace the user-defined data directly in the query string, because there is a risk of SQL injection.

I Google translated this text, I hope it seems correct.

    
answered by 02.03.2016 / 15:25
source