Quick workaround for #1969.

This commit is contained in:
Charles Leifer
2019-07-23 06:41:17 -05:00
parent 9fb1c89353
commit 9e4f1fa3ad
3 changed files with 29 additions and 2 deletions
+15
View File
@@ -460,6 +460,9 @@ class DatabaseProxy(Proxy):
return _savepoint(self)
class ModelDescriptor(object): pass
# SQL Generation.
@@ -6423,6 +6426,18 @@ class ModelAlias(Node):
self.__dict__['alias'] = alias
def __getattr__(self, attr):
# Hack to work-around the fact that properties or other objects
# implementing the descriptor protocol (on the model being aliased),
# will not work correctly when we use getattr(). So we explicitly pass
# the model alias to the descriptor's getter.
try:
obj = self.model.__dict__[attr]
except KeyError:
pass
else:
if isinstance(obj, ModelDescriptor):
return obj.__get__(None, self)
model_attr = getattr(self.model, attr)
if isinstance(model_attr, Field):
self.__dict__[attr] = FieldAlias.create(self, model_attr)
+5 -2
View File
@@ -1,6 +1,9 @@
from peewee import ModelDescriptor
# Hybrid methods/attributes, based on similar functionality in SQLAlchemy:
# http://docs.sqlalchemy.org/en/improve_toc/orm/extensions/hybrid.html
class hybrid_method(object):
class hybrid_method(ModelDescriptor):
def __init__(self, func, expr=None):
self.func = func
self.expr = expr or func
@@ -15,7 +18,7 @@ class hybrid_method(object):
return self
class hybrid_property(object):
class hybrid_property(ModelDescriptor):
def __init__(self, fget, fset=None, fdel=None, expr=None):
self.fget = fget
self.fset = fset
+9
View File
@@ -99,3 +99,12 @@ class TestHybridProperties(ModelTestCase):
query = Person.select().where(Person.full_name.startswith('huey c'))
huey_db = query.get()
self.assertEqual(huey_db.id, huey.id)
def test_hybrid_model_alias(self):
Person.create(first='huey', last='cat')
PA = Person.alias()
query = PA.select(PA.full_name).where(PA.last == 'cat')
self.assertSQL(query, (
'SELECT (("t1"."first" || ?) || "t1"."last") '
'FROM "person" AS "t1" WHERE ("t1"."last" = ?)'), [' ', 'cat'])
self.assertEqual(query.tuples()[0], ('huey cat',))