Django ORM是否具有与SQLAlchemy的Hybrid属性等效的功能? [英] Does Django ORM have an equivalent to SQLAlchemy's Hybrid Attribute?
问题描述
在 SQLAlchemy 中,是属性或应用于ORM映射类的方法
In SQLAlchemy, a hybrid attribute is either a property or method applied to an ORM-mapped class,
class Interval(Base):
__tablename__ = 'interval'
id = Column(Integer, primary_key=True)
start = Column(Integer, nullable=False)
end = Column(Integer, nullable=False)
def __init__(self, start, end):
self.start = start
self.end = end
@hybrid_property
def length(self):
return self.end - self.start
@hybrid_method
def contains(self,point):
return (self.start <= point) & (point < self.end)
@hybrid_method
def intersects(self, other):
return self.contains(other.start) | self.contains(other.end)
这允许在类和实例级别执行不同的行为,从而使使用相同代码评估SQL语句更加简单,
This allows for distinct behaviors at the class and instance levels, thus making it simpler to evaluate SQL statements using the same code,
>>> i1 = Interval(5, 10)
>>> i1.length
5
>>> print Session().query(Interval).filter(Interval.length > 10)
SELECT interval.id AS interval_id, interval.start AS interval_start,
interval."end" AS interval_end
FROM interval
WHERE interval."end" - interval.start > :param_1
现在在 Django 中,如果我有一个模型,
Now in Django, if I have a property on a model,
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
def _get_full_name(self):
"Returns the person's full name."
return '%s %s' % (self.first_name, self.last_name)
full_name = property(_get_full_name)
这是我了解,我不能 执行以下操作,
It is my understanding that I can not do the following,
Person.objects.filter(full_name="John Cadengo")
Django中是否有等效的SQLAlchemy的hybrid属性?如果没有,也许有一个通用的解决方法?
Is there an equivalent of SQLAlchemy's hybrid attribute in Django? If not, is there perhaps a common workaround?
推荐答案
很正确,您不能基于python属性应用django queryset过滤器,因为该过滤器在数据库级别运行.似乎在Django中没有等效的SQLAlchemy的hybrid属性.
You're right that you cannot apply django queryset filter based on python properties, because filter operates on a database level. It seems that there's no equivalent of SQLAlchemy's hybrid attributes in Django.
请在此处和
Please, take a look here and here, may be it'll help you to find a workaround. But, I think there is no generic solution.
这篇关于Django ORM是否具有与SQLAlchemy的Hybrid属性等效的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!