Django 如何保存多对多关系?
我几乎是在使用下面的代码(我把代码分了一点),我使用auto complete light加载用户,用户可以插入不同的人名(用户),用逗号分隔。问题是,当我尝试保存时,会出现以下错误Django 如何保存多对多关系?,django,django-models,django-forms,Django,Django Models,Django Forms,我几乎是在使用下面的代码(我把代码分了一点),我使用auto complete light加载用户,用户可以插入不同的人名(用户),用逗号分隔。问题是,当我尝试保存时,会出现以下错误 ValueError at /write/ "<Article: test1>" needs to have a value for field "article" before this many-to-many relationship can be used. forms.py class Ar
ValueError at /write/
"<Article: test1>" needs to have a value for field "article" before this many-to-many relationship can be used.
forms.py
class ArticleForm(forms.ModelForm):
people = forms.CharField(widget=autocomplete_light.TextWidget('UserAutocomplete'))
class Meta:
model = Article
views.py
def write(request):
if request.POST:
form = ArticleForm(request.POST)
if form.is_valid():
content = form.cleaned_data['content']
user = User.objects.get(username=request.user.username)
people_str = form.cleaned_data['accompanied']
people = [x.strip() for x in accompanied_str.split(',')]
article = Article(
content = content,
author = user,
)
for username in accompanied:
user = User.objects.get(username=username)
article.people.add(user)
article.save()
return HttpResponseRedirect('/success/')
为了创建关系,您需要双方的ID。新创建的项目还没有id。如果您先保存文章,然后向其中添加人员,它应该可以正常工作
article = Article(
content = content,
author = user,
)
article.save()
article.add(*User.objects.filter(username__in=accompanied))
通过在一次抓取中从用户列表中获取所有拥有用户名的用户,添加用户的过程可能会更便宜。我简直不敢相信这有多愚蠢,我已经在上面呆了3个小时了!谢谢。
article = Article(
content = content,
author = user,
)
article.save()
article.add(*User.objects.filter(username__in=accompanied))