简体   繁体   English

Django rest框架中的继承方法

[英]Inherit methods in Django rest framework

I'm new to learning django rest framework & python.我是学习 django rest 框架和 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

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.在这种情况下,定义了每个模型类中的每个字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM