문제

i don't know when and where a can call my method's which i define in model Class

models.py

class MyClass(models.Model):
    title = models.CharFiled(max_length=255, null=False)
    body = models.TextFiled(max_length=255, null=False)

    def body_formatted(self):
        return "formatted string {0}".format(body)

views.py
def object(request):
   object = MyClass.objects.all()
   return locals()

when and how i can called body_formatted method to modify my fields?

도움이 되었습니까?

해결책

There are quite a few mistakes in the code. Apart from this, the methods defined in a model class can be called on any instance of the model. In fact, a Model is a normal python class.

You need to modify the code as below:

#models.py
class MyClass(models.Model):
    title = models.CharField(max_length=255, null=False)
    body = models.TextField(max_length=255, null=False)

    def body_formatted(self):
        return "formatted string {0}".format(self.body)

#views.py
def myview(request):
   # Get a model instance corresponding to the first DB row
   obj = MyClass.objects.first()
   body_formatted = obj.body_formatted()    # Calling the model's method
   return HttpResponse(body_formatted)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top