在django中编辑并保存数据库中已存在的数据

时间:2013-03-04 05:58:34

标签: mysql django django-models

models.py是

class Book(models.Model):
    book_name=models.CharField(max_length=30)
    author_name=models.CharField(max_length=30)
    publisher_name=models.CharField(max_length=40)
    author=models.ForeignKey(Author)

    def __unicode__(self):
        ..........

class Author(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40)
    email = models.EmailField()
    age=models.IntegerField()

    def __unicode__(self):
        ........

    def books(self):
        return Book.objects.filter(author=self)

我需要执行编辑并将已存在的数据保存在数据库的表中。我正在使用2个模型。因为我是通过单个表执行相同的操作,所以要对两个表执行一些混乱。我是学习者django.plz的帮助我这个

请检查我的views.py是否有编辑选项。

def editbook(request,book_id):
    if request.POST:
        book_name =request.POST['book_name']
        publisher_name =request.POST['publisher_name']
    books=Book.objects.filter(book_id=book_id).update(book_name=book_name, publisher_name=publisher_name)

    first_name = request.POST.get('first_name')
        last_name = request.POST.get('last_name')
        email = request.POST.get('email')
        age = request.POST.get('age')
    author = Author.objects.update(first_name = first_name,last_name = last_name,email=email,age=age)
        return redirect('/index/')
    else:
        books = Book.objects.get(pk=book_id)
    return render_to_response('editbook.html',{'books':books},context_instance=RequestContext(request))

ya.this notl properlly.plz指导我如何执行。

1 个答案:

答案 0 :(得分:1)

def editbook(request,book_id):
   books = Book.objects.get(pk=book_id) 
   if request.POST:
        book_name = request.POST.get('book_name')
        publisher_name = request.POST.get('publisher_name')

        books.book_name = book_name
        books.publisher = publisher_name
        get_author = books.save()

        first_name = request.POST.get('first_name')
        last_name = request.POST.get('last_name')
        email = request.POST.get('email')
        age = int(request.POST.get('age'))

        author = Author.objects.get(pk=get_author.author_id)
        author.first_name = first_name
        author.last_name = last_name
        author.email = email
        author.age = age
        author.save()

        return redirect('/index/')

    return render_to_response('editbook.html',{
        'books':books
    },context_instance=RequestContext(request))