使用Django将多个相关对象添加到父模型

时间:2015-05-19 23:58:37

标签: python django

我尝试使用Django 多个相关对象添加到父对象。
我得到的错误:int() argument must be a string or a number, not 'Tag'

我的代码如下所示:

def ask(request):

    form = AskQuestionForm

    if request.method == 'POST':

        form = AskQuestionForm(request.POST)

        if form.is_valid():

            tags = request.POST.getlist('tags')

            # Category
            qcat = Category.objects.filter(id=request.POST.get('category')).first()

            o = Question.objects.create(
                title = request.POST.get('title'),
                body = request.POST.get('body'),
                category = qcat,
                user = request.user
            )

            for t in tags:
                rt = Tag.objects.get_or_create(word=t)
                o.tags.add(rt)

            return redirect('questions.index')

    return render(request, 'questions/ask.html', {
        'form' : form
    })

我想在问题对象中添加标签。我做错了什么?

1 个答案:

答案 0 :(得分:2)

get_or_create()返回(object, created)元组。因此,将标签创建更改为:

rt, _ = Tag.objects.get_or_create(word=t)