Django ORM是否具有SQLAlchemy的混合属性?

时间:2022-05-23 12:01:09

In SQLAlchemy, a hybrid attribute is either a property or method applied to an ORM-mapped class,

在SQLAlchemy中,混合属性是应用于ORM映射类的属性或方法,

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)

This allows for distinct behaviors at the class and instance levels, thus making it simpler to evaluate SQL statements using the same code,

这允许在类和实例级别执行不同的行为,从而使使用相同的代码评估SQL语句变得更加简单,

>>> 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

Now in Django, if I have a property on a model,

现在在Django中,如果我在模型上有属性,

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")

Is there an equivalent of SQLAlchemy's hybrid attribute in Django? If not, is there perhaps a common workaround?

在Django中是否有相当于SQLAlchemy的混合属性?如果没有,是否有一个共同的解决方法?

1 个解决方案

#1


2  

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.

你是对的,你不能应用基于python属性的django queryset过滤器,因为过滤器在数据库级别上运行。似乎在Django中没有SQLAlchemy的混合属性。

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.

请看这里和这里,它可能会帮助您找到解决方法。但是,我认为没有通用的解决方案。

#1


2  

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.

你是对的,你不能应用基于python属性的django queryset过滤器,因为过滤器在数据库级别上运行。似乎在Django中没有SQLAlchemy的混合属性。

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.

请看这里和这里,它可能会帮助您找到解决方法。但是,我认为没有通用的解决方案。