我尝试使用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
})
我想在问题对象中添加标签。我做错了什么?
答案 0 :(得分:2)
get_or_create()
返回(object, created)
的元组。因此,将标签创建更改为:
rt, _ = Tag.objects.get_or_create(word=t)