Does Django ORM have an equivalent SQLAlchemy hybrid attribute?

In SQLAlchemy , a hybrid attribute is either a property or a method applied to a class labeled 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 you to distinguish between class and instance behavior, making it easy 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 

Now in Django , if I have a property on the 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 full name." return '%s %s' % (self.first_name, self.last_name) full_name = property(_get_full_name) 

It is my understanding that I cannot do the following:

 Person.objects.filter(full_name="John Cadengo") 

Is there an equivalent SQLAlchemy hybrid attribute in Django? If not, is there a workaround possible?

+6
source share
1 answer

You are right that you cannot apply the django request filter based on python properties, because the filter works at the database level. There seems to be no equivalent to SQLAlchemy hybrid attributes in Django.

Please look here and here , perhaps this will help you find a workaround. But, I think there is no general solution.

+2
source

Source: https://habr.com/ru/post/924281/


All Articles