从视图调用模型方法

时间:2014-07-10 02:29:20

标签: python django django-models django-views

我试图从我的观点中调用我的models.py中定义的方法,但我收到此消息:

unbound method add_question_history() must be called with QuestionHistory instance as first argument (got User instance instead)

这是我的模特:

class QuestionHistory(models.Model):
    question = models.ForeignKey(Question, blank=True, null=True)
    user = models.OneToOneField('auth.User')
    created_at = models.DateTimeField(auto_now=True, auto_now_add=False)

def __unicode__(self):
    return unicode(self.question)

def add_question_history(user, question):
    qs = self.create(
        question = question,
        user = user
    )
    self.save()

这就是我试图在视图中调用此方法的方法:

QuestionHistory.add_question_history(request.user, question_ID)

1 个答案:

答案 0 :(得分:1)

您要做的是在没有实例的情况下调用实例方法

似乎你想要的是 classmethod

因此,要使代码正常工作,您可以先创建实例,也可以将add_question_history创建为 classmethod

制作一个实例:

class QuestionHistory(models.Model):
    question = models.ForeignKey(Question, blank=True, null=True)
    user = models.OneToOneField('auth.User')
    created_at = models.DateTimeField(auto_now=True, auto_now_add=False)

    def __unicode__(self):
        return unicode(self.question)

   def add_question_history(self, user, question):
       qs = self.objects.create(
               question = question,
               user = user
       )
      qs.save()
      #more stuff

 QuestionHistory().add_question_history(request.user, questionID)

制作课程方法:

class QuestionHistory(models.Model):
        question = models.ForeignKey(Question, blank=True, null=True)
        user = models.OneToOneField('auth.User')
        created_at = models.DateTimeField(auto_now=True, auto_now_add=False)

        def __unicode__(self):
            return unicode(self.question)

       @classmethod
       def add_question_history(cls, user, question):
           qs = cls.objects.create(
                   question = question,
                   user = user
           )
        qs.save()
        #stuff

 QuestionHistory.add_question_history(user,question)

为了更好地理解,请阅读this