How do I edit and delete data in Django?

和自甴很熟 提交于 2020-01-29 03:02:12

问题


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!

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


回答1:


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

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:

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

I suggest you take a look at the docs




回答2:


To do either of these you need to use something called queries.

check link below for really great documentation on that! (https://docs.djangoproject.com/en/2.2/topics/db/queries/)

To Delete Data:

b = ModelName.objects.get(id = 1)
b.delete()

This will delete the Object of the model w/ an ID of 1

To edit Data:

b = ModelName.objects.get(id = 1)
b.name = 'Henry'
b.save()

This will change the name of the Object of the model w/ an ID of 1 to be Henry




回答3:


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



来源:https://stackoverflow.com/questions/311188/how-do-i-edit-and-delete-data-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!