MasoniteFramework / orm

Masonite ORM is a beautiful Python ORM. It's also a nearly drop in replacement of the Orator ORM
https://orm.masoniteproject.com
MIT License
160 stars 47 forks source link

Ability to define custom computed properties on models #844

Closed lekhnath closed 9 months ago

lekhnath commented 1 year ago

Describe the feature as you'd like to see it Define computed property on Models

What do we currently have to do now?


class Product(Model):

    @property
     def amount_total(self):
        return self.rate * self.qty

Additional context This is just an example but it would be nice if we could define custom properties on model and also select these property dynamically using the select method. I've tried using __cast_map__ I could not manage to get the desired result. It is not selectable and the value returned from get method of Caster class also did not reflect in result.

Demo implementation of __cast_map__:

from masoniteorm.models import Model

class UsernameCaster:
    def get(self, value):
        return value.split('@')[0]

    def set(self, value):
        pass

class User(Model):
    __selects__ = ['id', 'email as username']
    __cast_map__ = {
        "username": UsernameCaster,
    }
josephmancuso commented 9 months ago

i think you're referring to mutators and accessors. if not ill reopen

https://orm.masoniteproject.com/models#accessors-and-mutators-getter-and-setter

josephmancuso commented 9 months ago

if you want to seect this you would have to use the add_select clause for the query builder. if you want the logic in the model you could use a scope and add it there