Is it correct, that in Web2Py you are not able to create custom methods within “models”, so that they could contain business logic you want models to implement?
In case of Django you can just do something like:
class Aircraft(models.Model):
'''I am an aircraft. I can fly, if I am created in Django.
'''
name = models.CharField(max_length=20)
def fly(self):
# ... some advanced logic here ...
return 'I am flying'
But is it possible to do something like that (create custom methods) in Web2Py without the need to write the whole ORM system from the beginning or to share single method between instances of all the tables? Is there any established way to do that? For example:
db.define_table("aircrafts",
Field("name", type="string", length=20)
)
aircraft = db(db.aircrafts).select().first()
# I am an aircraft too, please make me fly
aircraft.fly()
Yes, you can define virtual fields:
or
In the first example above, the “fly” value is automatically calculated for all records when they are selected. In the second example, the calculation is lazy and only executed when
.fly()is actually called on a specific record.You can also do this with old style virtual fields, which may be better for complex functions.
Note, this is handled differently from Django because web2py uses a database abstraction layer (DAL) rather than an ORM. Tables are not modeled as custom classes but as instances of the DAL
Tableclass.