如何在Django中编辑和删除数据?

时间:2021-08-08 09:18:08

I am using django 1.0 and I have created my models using the example in the Django book. I am able to perform the basic function of adding data; now I need a way of retrieving that data, loading it into a form (change_form?! or something), EDIT it and save it back to the DB. Secondly how do I DELETE the data that's in the DB? i.e. search, select and then delete!

我正在使用django 1.0,我使用Django书中的示例创建了我的模型。我能够执行添加数据的基本功能;现在我需要一种检索数据的方法,将其加载到表单中(change_form ?!或其他),编辑它并将其保存回数据库。其次,如何删除数据库中的数据?即搜索,选择然后删除!

Please show me an example of the code I need to write on my view.py and urls.py for perform this task.

请给我一个示例,我需要在view.py和urls.py上编写代码来执行此任务。

2 个解决方案

#1


22  

Say you have a model Employee. To edit an entry with primary key emp_id you do:

假设你有一个模型员工。要编辑具有主键emp_id的条目,您可以:

emp = Employee.objects.get(pk = emp_id)
emp.name = 'Somename'
emp.save()

to delete it just do:

删除它只是做:

emp.delete()

so a full view would be:

所以完整视图将是:

def update(request, id):
   emp = Employee.objects.get(pk = id)
   #you can do this for as many fields as you like
   #here I asume you had a form with input like <input type="text" name="name"/>
   #so it's basically like that for all form fields
   emp.name = request.POST.get('name')
   emp.save()
   return HttpResponse('updated')

def delete(request, id):
   emp = Employee.objects.get(pk = id)
   emp.delete()
   return HttpResponse('deleted')

In urls.py you'd need two entries like this:

在urls.py中你需要两个这样的条目:

(r'^delete/(\d+)/$','myproject.myapp.views.delete'),
(r'^update/(\d+)/$','myproject.myapp.views.update'),

I suggest you take a look at the docs

我建议你看看文档

#2


-4  

Read the following: The Django admin site. Then revise your question with specific details.

阅读以下内容:Django管理站点。然后用具体细节修改您的问题。

#1


22  

Say you have a model Employee. To edit an entry with primary key emp_id you do:

假设你有一个模型员工。要编辑具有主键emp_id的条目,您可以:

emp = Employee.objects.get(pk = emp_id)
emp.name = 'Somename'
emp.save()

to delete it just do:

删除它只是做:

emp.delete()

so a full view would be:

所以完整视图将是:

def update(request, id):
   emp = Employee.objects.get(pk = id)
   #you can do this for as many fields as you like
   #here I asume you had a form with input like <input type="text" name="name"/>
   #so it's basically like that for all form fields
   emp.name = request.POST.get('name')
   emp.save()
   return HttpResponse('updated')

def delete(request, id):
   emp = Employee.objects.get(pk = id)
   emp.delete()
   return HttpResponse('deleted')

In urls.py you'd need two entries like this:

在urls.py中你需要两个这样的条目:

(r'^delete/(\d+)/$','myproject.myapp.views.delete'),
(r'^update/(\d+)/$','myproject.myapp.views.update'),

I suggest you take a look at the docs

我建议你看看文档

#2


-4  

Read the following: The Django admin site. Then revise your question with specific details.

阅读以下内容:Django管理站点。然后用具体细节修改您的问题。