[英]How can I use the Model's function?
I have a TypeModel
model, and in it there is a : 我有一个TypeModel
模型,其中有一个:
class TypeModel(models.Model):
name = models.CharField(max_length=22)
type = models.CharField(max_length=12)
ch = models.CharField(max_length=44, null=True)
def print(self, name, type):
t = TypeModel.objects.create(name=name, type=type)
print('success - ' + t.name)
I want to invoke the print
method like this: 我想这样调用print
方法:
class TypeModelCreateAPIView(APIView):
permission_classes = [AllowAny]
def post(self, request):
TypeModel.print() # Can I invoke like this
return Response(status=HTTP_200_OK, data='')
Whether I can invoke the function of model like this? 我是否可以像这样调用模型的功能? if not, how to realize the Class method of model? 如果不是,如何实现模型的Class方法?
You can use staticmethod: 您可以使用staticmethod:
@staticmethod
def print(name, type):
t = TypeModel.objects.create(name=name, type=type)
print('success - ' + t.name)
Yes, this can be done with the staticmethod annotation 是的,这可以通过staticmethod注释完成
class TypeModel(models.Model):
name = models.CharField(max_length=22)
type = models.CharField(max_length=12)
ch = models.CharField(max_length=44, null=True)
@staticmethod
def print(name, type):
t = TypeModel.objects.create(name=name, type=type)
print('success - ' + t.name)
Please note, that a static method does not have the implicit self
as first argument. 请注意,静态方法没有隐式self
作为第一个参数。
Currently print
is defined as an instance method. 当前print
被定义为实例方法。 You would have to create an instance of TypeModel
to call it. 您必须创建TypeModel
实例才能调用它。 Like: 喜欢:
model = TypeModel()
model.print()
Or you could use the @staticmethod
decorator: 或者您可以使用@staticmethod
装饰器:
@staticmethod
def print(name, type):
t = TypeModel.objects.create(name=name, type=type)
print('success - ' + t.name)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.