我在模型的自定义方法中加入了一些逻辑。
我这样做是因为在视图中使用了这些方法
我的模特:
class Quiz(models.Model):
# Some fields..
# And some example methods that contain a logic
def get_manage_questions_url(self):
return reverse('manage-questions', kwargs={'slug': self.slug})
def get_likes_count(self):
return self.likes.count()
def get_completed_count(self):
return QuizManager.objects.filter(quiz=self, completed=True).count()
def like_quiz(self, quiz, user):
data = {}
if user in quiz.likes.all():
quiz.likes.remove(user)
data['liked'] = False
else:
quiz.likes.add(user)
data['liked'] = True
data['likes'] = quiz.get_likes_count()
return data
def increase_views(self):
self.views += 1
self.save(update_fields=('views',))
我有一个问题:
我是否需要在模型中编写所有自定义方法,还是需要将此类方法放入经理类型的QuizManager(models.Manager)并在测验模型中定义“对象”属性?