Using instance methods with Django Model
I'm trying to implement for methods for eac Model object in my project. get_all() , get_by_id(),add(),remove() and maybe others. I need to use them by each object . When I declare an object automatically can call one of 开发者_运维百科those methods. The problem , I don't want to duplicate the code of the four methods in each class . Is there a way to write them once, and link them to each object. I heared about instance methods in python. How can use this. Please a help Thanks ...
You can have a base manager which has all these methods and inherit them. Django model and manager inheritance
class MyModel(models.Model):
def get_all():
return <something>
class A(MyModel):
pass
class B(MyModel):
pass
You really should seperate row-level actions (like delete(), get_some_calculated_attribute()) which go in Model classes from table level actions (like create(), filter()) which go in Manager classes.
精彩评论