django manytomany 字段使用 through 和 formwizard

Posted

技术标签:

【中文标题】django manytomany 字段使用 through 和 formwizard【英文标题】:django manytomany field using through and formwizard 【发布时间】:2014-02-04 19:48:56 【问题描述】:

我正在尝试创建一个非常复杂的表单并使用表单向导将其分解。我要做的第一件事是让 ManyToManyField 使用 through 来显示,然后我需要弄清楚如何让它全部保存。

#models.py
----------------------

class Meat(models.Model):
    name = models.charField(max_length=200)
    company = models.CharField(max_length = 200)

class Starch(models.Model):
    name = models.CharField(max_length=200)
    company = models.CharField(max_length=200)



class Recipe(models.Model):
    name = models.CharField(max_length=200)
    description = models.TextField(help_text='Please describe the finished dish')
    meat = models.ManyToManyField('Meat' through='RecipeMeat')
    meat_notes = models.TextField()
    starch = models.ManyToManyField('Starch' through='RecipeStarch')
    starch_notes = models.TextField()



class RecipeMeat(models.Model):
    recipe = models.ForeignKey(Recipe)
    meat = models.ForeignKey(Meat)
    qty = models.FloatField()

class RecipeStarch
    recipe = models.ForeignKey(Recipe)
    starch = models.ForeignKey(Starch)
    qty = models.FloatField()

.

#forms.py
-------------------

class RecipeForm(forms.ModelForm):
    class Meta:
        model = Recipe
        fields = ('name', 'description')


class RecipeMeatForm(forms.ModelForm):
    class Meta:
        model = RecipeMeat

class RecipeMeatNotesForm(forms.ModelForm):
    class Meta:
        model = Recipe
        fields = ('meat_notes',)

class RecipeStarch(forms.ModelForm):
    class Meta:
        model = RecipeStarch

class RecipeStarchNotesForm(forms.ModelForm):
    class Meta:
        model = Recipe
        fields = ('starch_notes')

MeatFormSet = inlineformset_factory(Recipe, RecipeMeat, form=RecipeMeatForm, extra=1)

.

#views.py
---------------------------


class CreateRecipeWizard(SessionWizardView):
    template_name = "create-recipe.html"
    instance =  None
    file_storage = FileSystemStorage(location= 'images')

    def dispatch(self, request, *args, **kwargs):
        self.instance = Recipe()
        return super(CreateRecipeWizard, self).dispatch(request, *args, **kwargs)

    def get_form_instance( self, step ):
        return self.instance

    def done( self, form_list, **kwargs ):
         self.instance.save()
        return HttpResponseRedirect(reverse(all-recipes))

.

#urls.py
------------------------------

 url(r'^create-recipe/$', views.CreateRecipeWizard.as_view([RecipeForm, MeatFormSet, RecipeMeatNotesForm, RecipeStarchNotesForm]), name='create-recipe'),

.

我是这个 django 东西的新手。食谱部分更长更复杂,但模式几乎相同。如果有人能帮助我正确地指出如何让我的 ManyToManyField 使用 through 部分弄清楚或指出正确的方向,那将不胜感激。

【问题讨论】:

【参考方案1】:

要在表单向导进程中保存多对多关系,您可以执行以下操作;

def done(self, form_list, **kwargs):
    form_data_dict = self.get_all_cleaned_data()
    m2mfield = form_data_dict.pop('m2mfield')

    instance = form_list[0].save()
    for something in m2mfield:
        instance.m2mfield.add(something)

    return render_to_response(
        'done.html', ,
        context_instance=RequestContext(self.request)
    )

在此示例中,列表中的第一个表单是 ModelForm,用于我正在尝试创建的东西,它有一个 ManyToManyField 到另一个模型,我在此过程中有第二个表单。所以我抓取第一个表单并保存它,然后从第二个表单的清理数据中抓取字段并将选定的选项保存到 M2M 字段。

【讨论】:

以上是关于django manytomany 字段使用 through 和 formwizard的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 Django Rest Framework 向 ManyToMany 字段添加数据?

Django:快速检索manyToMany字段的ID

有多少种方法可以使用 Django ORM 获取 ManyToMany 字段数据

django manytomany 字段使用 through 和 formwizard

Django 中的 OneToOne、ManyToMany 和 ForeignKey 字段有啥区别?

Django ManyToMany 字段上的自定义列名