请告诉我如何使用模型的方法删除表中的条目。
现在我使用以下代码从视图中删除一个条目:
view.py:
def admin_sends(request):
if request.method == 'POST':
post = request.POST
Sends.objects.filter(id=post['delete']).delete()
all_entries = Sends.objects.all()
return render_to_response('admin_sends.html', {
'all_entries': all_entries
})
models.py:
from django.db import models
class Sends(models.Model):
name = models.CharField(max_length=30)
email = models.EmailField()
subject = models.CharField(max_length=60)
message = models.TextField(max_length=500)
但明智的做法是保留删除模型类中条目的功能: models.py
from django.db import models
class Sends(models.Model):
name = models.CharField(max_length=30)
email = models.EmailField()
subject = models.CharField(max_length=60)
message = models.TextField(max_length=500)
def delete_entrie(self, del_id):
?????????????????????????
views.py:
def admin_sends(request):
if request.method == 'POST':
post = request.POST
??????????????????????????
all_entries = Sends.objects.all()
return render_to_response('admin_sends.html', {
'all_entries': all_entries
})
答案 0 :(得分:1)
您可以通过这种方式添加类方法,使用classmethod修饰方法:
class Sends(models.Model):
...
@classmethod
def delete_entrie(cls, del_id):
cls.objects.filter(id=del_id).delete()
称之为:
Sends.delete_entire(id_)
答案 1 :(得分:0)
在Django的模型上已经有了一个方法delete
。
所以你的观点看起来像::
def admin_sends(request):
if request.method == 'POST':
post = request.POST
Sends.objects.get(id=post['delete']).delete()
...
含义“获取具有匹配ID的对象并在其上调用delete方法。”