[英]Add multiple related objects to a parent model with Django
I'm trying to add multiple related objects to a parent object with Django. 我正在尝试使用Django 将 多个相关对象添加到父对象。
The error i get: int() argument must be a string or a number, not 'Tag'
我得到的错误: int() argument must be a string or a number, not 'Tag'
My code looks like this: 我的代码如下所示:
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
})
I want to add tags to question object. 我想向问题对象添加标签。 What am I doing wrong? 我究竟做错了什么?
get_or_create()
returns a tuple of (object, created)
. get_or_create()
返回(object, created)
的元组 。 So change the tag creation to: 因此,将标记创建更改为:
rt, _ = Tag.objects.get_or_create(word=t)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.