在Django中抓取对象

时间:2018-08-03 14:25:34

标签: python django

这可能是非常简单和基本的,但是我正在努力抓住Django中新创建的对象。它是用于基本库样式的应用程序。在模型中,我这样做是为了创建Book对象:

def add_book(self, postData, user_id):
    title = postData['title']
    first_name = postData['first_name']
    last_name = postData['last_name']
    user_obj = User.objects.get(id=user_id)

    if not Author.objects.filter(first_name=first_name, last_name=last_name).exists():
        author_obj = Author.objects.create(first_name=first_name, last_name=last_name)
    else:
        author_obj = Author.objects.get(first_name=first_name, last_name=last_name)

    return self.create(title=postData['title'], created_by=user_obj, author=author_obj)

然后在视图中,我调用该方法,并希望重定向到专门针对该新创建对象的页面。我认为您可以看到我的大部分代码都写完了,但是不知道该用什么代替“ ????”。

def books_add(request):
    if request.method == "POST":
        errors = Book.objects.book_validation(request.POST)

    if not errors:
        Book.objects.add_book(request.POST, request.session['uid'])
        book_id = Book.objects.get(????).id
        return redirect('/books/book/{}/'.format(book_id))
    else:
        context = {
            'errors' : errors,
        }

2 个答案:

答案 0 :(得分:0)

第一部分使用get_or_create检索或创建模型条目

def add_book(self, postData, user_id):
    title = postData['title']
    first_name = postData['first_name']
    last_name = postData['last_name']
    user_obj = User.objects.get(id=user_id)

    author_obj, created = Author.objects.get_or_create(first_name=first_name, last_name=last_name)

    return self.create(title=postData['title'], created_by=user_obj, author=author_obj)

第二部分return self.create返回Book实体:

def books_add(request): 
    if request.method == "POST": 
        errors = Book.objects.book_validation(request.POST)
    if not errors:
        book = Book.objects.add_book(request.POST, request.session['uid'])
        return redirect('/books/book/{}/'.format(book.id))
    else:
        context = {
            'errors' : errors,
        }

答案 1 :(得分:0)

这里有一些问题。至少,在进一步学习之前,请先阅读Django Forms。这就是创建对象的视图的样子:

def add_book(request):
    if request.POST:
        author, created = Author.objects.get_or_create(first_name=first_name,
                                                       last_name=last_name)

        book = Book(title = request.POST['title'],  
                    user_obj = request.GET['user'],
                    author = author,)
        book.save()

        return redirect('/books/book/{}/'.format(book.id))

    else:
        return render(request, 'book_form.html')

您确实需要研究ModelForms来处理您的POST。但首先要看Forms