简体   繁体   中英

How can I use the Model's function?

I have a TypeModel model, and in it there is a :

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:

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?

You can use 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

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.

Currently print is defined as an instance method. You would have to create an instance of TypeModel to call it. Like:

model = TypeModel()
model.print()

Or you could use the @staticmethod decorator:

@staticmethod
def print(name, type):
    t = TypeModel.objects.create(name=name, type=type)
    print('success - ' + t.name)  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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