Jaymon / prom

A PostgreSQL or SQLite orm for Python
MIT License
22 stars 4 forks source link

easier to use Model #78

Closed Jaymon closed 4 years ago

Jaymon commented 5 years ago

we have used some variation of this base class in a few projects:

class Orm(prom.Orm):
    @property
    def timestamp(self):
        return self.datestamp(self._created)

    def __pout__(self):
        return self.fields

    def __getattr__(self, k):
        """The primary purpose of this is to convert self.foo to an actual object
        if there is a field name like foo_id
        """
        instance = None
        raise_error = True
        for field in self.schema.fields.values():
            if field.name == "{}_id".format(k):
            #if field.name.startswith("{}_".format(k)) and field.name.endswith("_id"):
                # NOTE -- another way to do this might be to just use field._type
                # and pass that into self.query.ref(field._type)
                schema = field.schema
                if schema:
                    orm_class = schema.orm_class
                    if orm_class:
                        raise_error = False
                        instance = orm_class.query.get_pk(getattr(self, field.name))

            # TODO -- allow is_NAME() to check if NAME is a bool and if it is return
            # true if NAME is true otherwise false, this way you could have a foo property
            # and be able to do is_foo() to check if it is true which I like a bit better
            # than just Instance.foo

            # TODO -- foo_id on Foo instance should return self.pk
        if raise_error:
            raise AttributeError(k)

        return instance

    # TODO -- jsonable that gets the class name and adds _id at the end for pk. so Foo.pk would be put
    # into the returned jsonable dict with 'foo_id': self.pk

It would be great to implement the todo also, so it would take _id and convert it to foo_id, I'm not sure if it this should be the default Model class but it would be nice to have the option to just easily pull this into other projects.

The above class was pulled from Reach, and there might be tests for it somewhere in those tests

Jaymon commented 4 years ago

satisfies the jsonable() todo in the above class

    def jsonable(self):
        d = super(Orm, self).jsonable()
        class_name = self.__class__.__name__.lower()
        d["{}_id".format(class_name)] = self.pk
        return d