Inherit methods in Django rest framework

77 views Asked by At

I'm new to learning django rest framework & python. I'm currently trying to inherit a few methods to which I don't know how. An alternative is I copy the same code which is code replication and against code design principles.

An example of what I what to do :

Class A (models.Model)-----> 

field1 = models()
field2 = models()
field3 = models()
field4 = models()


   @classmethod
    def method1():
       return something

    def method2():
       return something


Class B (models.Model)----->
 
field5 = models() - New field, no relation to Class A fields
field6 = models() - New field, no relation to Class A fields
field7 = models() - New field, no relation to Class A fields
field8 = models() - "Here I wish to link field8 to class A so that filed8 is also referenced  while viewing Class A fields .The relation I wish to establish is Many to One using Foreign Key"


    @classmethod
    "Here I wish to execute the 2 methods from Class A that are already defined, so that when When Class B is called , the 2 methods of Class A are also executed along with the new method of Class B itself"
    
    def method3(): ----> New method of class B.
       return something

1

There are 1 answers

0
Shishir Subedi On

you can make a Common model class which have fields and methods common for other class. For example

class Common(models.Model):
    common_field1 = models.TextField()
    common_field2 = models.TextField()
    
    def common_method(self):
        pass
    
    class Meta:
        abstract = True

class NewModelA(Common):
    # ... models A fields
    # ... models A methods
    pass

class NewModelB(Common):
    # ... models B fields
    # ... models B fields
    pass

Note: you will get related name issue when using relational field in common models. In that case defined each field in each models class.