保存ManyToMany字段数据的问题

时间:2017-05-13 16:48:26

标签: python django python-3.x django-1.10

我有2个 ManyToManyField 的模态。我试图保存表单时遇到问题。为什么save_m2m()方法不起作用?

正如您在function字段的表单中看到的,我使用了ModelChoiceField,而对于program字段,我使用了ModelMultipleChoiceField

modals.py:

class Requirement(models.Model):
    group_requirement = models.ForeignKey(GroupRequirement, on_delete=models.CASCADE)

    function = models.ManyToManyField("Function")
    program = models.ManyToManyField('Program')

forms.py:

class RequirementForm(forms.ModelForm):
    function = forms.ModelChoiceField(widget=Select2Widget(), queryset=Function.objects.none())
    program = forms.ModelMultipleChoiceField(widget=Select2MultipleWidget(), queryset=Program.objects.none())

    class Meta:
        model = Requirement
        fields = ('function', 'program')

    def __init__(self, all_functions, all_programs, *args, **kwargs):
        super(RequirementForm, self).__init__(*args, **kwargs)
        self.fields['function'].queryset = all_functions
        self.fields['program'].queryset = all_programs

views.py:

def requirement_add(request, project_id, group_requirement_id):
    group_requirement = get_object_or_404(GroupRequirement, pk=group_requirement_id)

    all_functions = Function.objects.filter(project=project_id)
    all_programs = Program.objects.filter(project=project_id)

    if request.method == 'POST':
        requirement_form = RequirementForm(data=request.POST, all_functions=all_functions, all_programs=all_programs)
        if requirement_form.is_valid():
           requirement = requirement_form.save(commit=False)
           requirement.group_requirement = group_requirement
           requirement.save()
           requirement_form.save_m2m()

错误:

Traceback (most recent call last):
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\exception.py", line 39, in inner
    response = get_response(request)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Nurzhan\PycharmProjects\RMS\project\views.py", line 1397, in requirement_add
    requirement_form.save_m2m()
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\forms\models.py", line 436, in _save_m2m
    f.save_form_data(self.instance, cleaned_data[f.name])
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\models\fields\related.py", line 1573, in save_form_data
    getattr(instance, self.attname).set(data)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\models\fields\related_descriptors.py", line 928, in set
    objs = tuple(objs)
TypeError: 'Function' object is not iterable

1 个答案:

答案 0 :(得分:0)

我的问题是我试图通过ManyToManyField将一个对象保存到ModelChoiceField。 ManyToManyField期望queryset。我决定从表单字段中获取数据并通过以下代码将其保存在视图中:

<强> views.py:

function= requirement_form.cleaned_data['function']
programs = requirement_form.cleaned_data['programs']

requirement= requirement_form.save(commit=False)

requirement.function.add(function)
for program in programs:
    requirement.program.add(program)