您可以在Django模型中定义一个将使用.save()函数的函数。
Class Restaurant(models.Model)
name = models.CharField(max_length=25)
rating = models.PositiveIntegerField(validators=[MaxValueValidator(100), MinValueValidator(0)], default=50)
def change_rating(self, value)
self.rating += value
self.rating.save()
这会有用吗?这是最佳做法吗?
在像这样的视图中完成此操作是否更好:
*views.py
def change_rating(name, amount):
res = Restaurant.objects.get(name=name)
res.rating += amount
res.save()
感谢您的帮助!
答案 0 :(得分:-1)
我会为这种情况建议模型经理
<强> model_managers.py 强>
getString
<强> models.py 强>
function getString(data){
var processedStr = ''
if (data.res2[i].paid_type == 1) {
if (data.res3.Status == "success") {
processedStr += '<span class="input-group-btn" style="padding-top:10px;">' +
'<button class="btn btn-info" type="button">Analysis 1</button>' +
'</span>'
}else {
processedStr += '<label style="padding:10px 10px;">' + data.res2[i].Paper_Name + '</label>' +
'<span class="input-group-btn" style="padding-top:10px;">' +
'<button class="btn btn-info" type="button">Analysis 1</button>' +
'</span>'
}
} else {
processedStr += '<label style="padding:10px 10px;">' + data.res2[i].Paper_Name + '</label>' +
'<span class="input-group-btn" style="padding-top:10px;">' +
'<button class="btn btn-info" type="button">Buy</button>' +'</span>' +
}
return processedStr;
}
执行命令
from django.db import models
class CustomManager(models.Manager):
def change_rating(self, value, **kwargs):
x = self.get(**kwargs)
x.rating += value
x.save()