2012-08-31 10 views
6

En SQLAlchemy, un hybrid attribute es o bien un método property o aplicado a una clase ORM-asignada,¿Django ORM tiene un equivalente al atributo híbrido de SQLAlchemy?

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) 

Esto permite distintos comportamientos a nivel de clase e instancia, por lo que es más fácil de evaluar las sentencias SQL utilizando el mismo código,

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

Ahora en Django, si tengo una propiedad en un modelo,

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) 

Es mi understanding que puedo no hacer lo siguiente,

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

¿Existe un equivalente de atributo híbrido de SQLAlchemy en Django? Si no, ¿hay quizás una solución común?

Respuesta

2

Tiene razón en que no puede aplicar el filtro django queryset en función de las propiedades de python, porque el filtro funciona en un nivel de base de datos. Parece que no hay un equivalente de los atributos híbridos de SQLAlchemy en Django.

Por favor, eche un vistazo a here y here, puede ser que le ayudará a encontrar una solución. Pero, creo que no hay una solución genérica.

Cuestiones relacionadas