On Wed, Jul 17, 2013 at 4:02 AM, Luis Francisco Jesus Masuelli Bonanni < [email protected]> wrote:
> A feature I would really appreciate (as devs in > http://stackoverflow.com/questions/12217763/does-django-orm-have-an-equivalent-to-sqlalchemys-hybrid-attribute, > at least) is the Hybrid Property feature present in SQLAlchemy. They would > really contribute to DRY principle. > > In django this would allow using it as a left-side for the key=value in a > filter query (in sqlalchemy they filter by <Class>.<property> as part of an > expression ). Example: > > class Purchase(models.Model): > first_name = CharField(...) > last_name = CharField(...) > ... > > @hybrid_property > def full_name(self): > return self.first_name + ' ' + self.full_name > > or ... > > class ProductEntry(models.Model): > purchase = ForeignKey(Purchase, related_name='product_entries') > onpurchase_price = DecimalField(...) > product = ForeignKey(Product) > quantity = DecimalField(...) > ... > > @hybrid_property > def cost(self): > return self.onpurchase_price * self.quantity > > > ... being those queries valid and working as expected > > Person.objects.filter(full_name__ilike='Martin') > ProductEntry.objects.filter(cost__lt=5000.0) #SQLAlchemy would use > ProductEntry.cost < 5000.0 > To dust off an old trope that I haven't used in a while…. … and a pony! Seriously -- what you've described sounds interesting, and the idea isn't a new one. Depending on exactly what you're intending, you could be describing: * A denormalized property. That is, an extra column is stored in the database with the computed value. * A virtual property - that is, there's no extra column, but you can use the property in queries, and it will be rolled out as a computed alias column in queries. Both of these have been proposed in the past (ticket #8946 for denormalized properties, for example). In the meantime, both of these can be done with the ORM as it stands. There are a couple of denormalized property implementations out in the wild; failing that, you can handle it with a normal Django field, populated in the model's save() method. Virtual properties can be emulated using an extra() clause in your query. It's not as elegant as the syntax you describe, but it works. So - functionally, what you describe can be done. What's missing is someone to polish the concepts into a patch for inclusion into Django's repository. If this is something that interests you - get hacking! :-) Yours, Russ Magee %-) -- You received this message because you are subscribed to the Google Groups "Django developers" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To post to this group, send email to [email protected]. Visit this group at http://groups.google.com/group/django-developers. For more options, visit https://groups.google.com/groups/opt_out.
