我正在尝试创建一个视图来更新模型。该模型具有ManyToMany关系。我在表单中使用ModelMultipleChoiceField,它在m2m表中查询值列表。我希望能够在更新记录时更新/更改记录上的m2m属性。当我提交此表格(更新)时,我得到了
用作表达式
的子查询返回的多行我希望有多个值,但我的代码没有处理它。
感谢您的帮助。
Models.py
class Activities(models.Model):
user = models.ForeignKey(User)
url = models.ForeignKey(Link)
name = models.CharField(max_length=60)
desc = models.CharField(max_length=250)
created = models.DateTimeField(auto_now_add=True)
done = models.BooleanField(default=False)
def __unicode__(self):
return u'%s' % (self.link.url)
class Groups (models.Model):
group = models.CharField(max_length=64)
desc = models.CharField(max_length=250)
created = models.DateTimeField(auto_now_add=True)
activity = models.ManyToManyField(Activities)
active_yn = models.BooleanField(default=True)
def __unicode__(self):
return self.group
class ActivitiesForm(ModelForm):
class Meta:
model = Activities
class GroupsForm(ModelForm):
class Meta:
model = Groups
forms.py (我认为问题在于:group = forms.ModelMultipleChoiceField( queryset = Groups.objects.all(),
#Add/Replace data in Activity Save
# radio buttons
choices = ( (1,'Yes'),(0,'No'),
)
# activity groups
class ActivitySaveForm(forms.Form):
url = forms.URLField(
label=u'URL',
widget=forms.TextInput(attrs={'size': 64})
)
name = forms.CharField(
label=u'Activity Name',
widget=forms.TextInput(attrs={'size': 64})
)
desc = forms.CharField(
label=u'Describe it',
widget=forms.TextInput(attrs={'size': 250})
)
group = forms.ModelMultipleChoiceField(queryset=Groups.objects.all(), required=True, widget=forms.CheckboxSelectMultiple
)
done = forms.TypedChoiceField(choices=choices, widget=forms.RadioSelect, coerce=int
)
views.py 第二个问题是:如果我不想返回id但想要在模型中返回不同的值,我如何使用Groups.objects.get_or_create( id = group )以外的其他内容( Groups.group)。
def activity_save_page(request):
if request.method == 'POST': # If the form has been submitted...
form = ActivitySaveForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
url, dummy = Link.objects.get_or_create(
url=form.cleaned_data['url']
)
act, created = Activities.objects.get_or_create(
user=request.user,
url=url
)
act.desc = form.cleaned_data['desc']
if not created:
act.groups_set.clear()
group = form.cleaned_data['group']
for groups in group:
group, dummy = Groups.objects.get_or_create(id=group)
act.groups_set_add(group)
act.save()
return HttpResponseRedirect(
'/user/%s/' % request.user.username
)
else:
form = ActivitySaveForm()
variables = RequestContext(request, {
'form': form
})
return render_to_response('activity_save.html', variables)
最后,如果你需要追溯回溯。
Request Method: POST
Request URL: http://127.0.0.1:8000/activity_save/
Django Version: 1.3.1
Python Version: 2.7.2
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'poc.location',
'django.contrib.admin',
'django.contrib.admindocs',
'south']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.csrf.CsrfResponseMiddleware')
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/home/footbook/webapps/fb/poc/../poc/location/views.py" in activity_save_page
327. group, dummy = Groups.objects.get_or_create(id=group)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py" in get_or_create
135. return self.get_query_set().get_or_create(**kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in get_or_create
378. return self.get(**lookup), False
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in get
344. num = len(clone)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in __len__
82. self._result_cache = list(self.iterator())
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in iterator
273. for row in compiler.results_iter():
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py" in results_iter
680. for rows in self.execute_sql(MULTI):
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py" in execute_sql
735. cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/util.py" in execute
34. return self.cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/postgresql_psycopg2/base.py" in execute
44. return self.cursor.execute(query, args)
Exception Type: DatabaseError at /activity_save/
Exception Value: more than one row returned by a subquery used as an expression
我认为我有错误的方法来获取数据,但不确定我应该使用什么。关于此错误有大量信息,但我找不到符合此需求的解决方案。谢谢你的帮助。
答案 0 :(得分:2)
追溯说问题就在这里:
File "/home/footbook/webapps/fb/poc/../poc/location/views.py" in activity_save_page
327. group, dummy = Groups.objects.get_or_create(id=group)
我认为问题是你以混乱的方式使用'群'和'群'。你实际上并没有在任何地方使用“群组”
group = form.cleaned_data['group'] <--- first you set group to a list from your form
for groups in group: <--- then you use 'groups' to indicate *one* group from the list
group, dummy = Groups.objects.get_or_create(id=group) <-- then you assign the list to the 'id' parameter.
你的意思是:
groups = form.cleaned_data['group']
for group in groups:
this_group, dummy = Groups.objects.get_or_create(id=group)
# do something with this_group
如果不仔细查看您的代码,我不知道这是否真的适用于您正在做的事情。