Django:形式和many2many关系使用通过关系

时间:2015-06-27 13:12:36

标签: django forms model

我正在尝试解决涉及" many2many"关系使用规范。 我已经尝试过使用inline_factory,但我无法解决问题。

我有这些表

class Person(models.Model):
    id = models.AutoField(primary_key=True)  
    fullname = models.CharField(max_length=200)
    nickname = models.CharField(max_length=45, blank=True)

    class Meta:
        db_table = 'people'

class Role(models.Model):
        role = models.CharField(max_length=200)
    class Meta:
        verbose_name_plural = 'roles'
        db_table = 'roles'

class Study(models.Model):
    id = models.AutoField(primary_key=True) 
    title = models.CharField(max_length=255)
    description = models.CharField(max_length=1000)
    members = models.ManyToManyField(Person, through='Studies2People')

    class Meta:
        db_table = 'studies'

class Studies2People(models.Model):
    person = models.ForeignKey(Person)
    role = models.ForeignKey(Role)
    study = models.ForeignKey(Study)

    class Meta:
        verbose_name_plural = 'studies2people'
        db_table = 'studies2people'
        unique_together = (('person', 'role', 'study'),)
#forms.py
from .models import Study, Person, Role, Studies2People
class RegisterStudyForm(ModelForm):
    class Meta:
        model = Study
        fields = '__all__'

#View.py
class StudyCreateView(CreateView):
    template_name = 'managements/register_study.html'
    model = Study
    form_class = RegisterStudyForm
    success_url = 'success/'

    def get(self, request, *args, **kwargs):
        self.object = None
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        return self.render_to_response(self.get_context_data(form=form))

上面的代码创建了一个类似的表单:

Study.Title
Study.description
List of People

我想创建一个表单来填写所有涉及Studies2People的字段:

Study.Title
Study.description
Combo(people.list)
Combo(Role.list)

也许我应该从Studies2People开始,但我不知道如何展示" inline"涉及的形式。

提前致谢 下进行。

1 个答案:

答案 0 :(得分:0)

等待某人能够通过一些例子解释m2m与通过(模型和视图)的关系,我以不同的方式解决了我的问题。

我创造了三种形式。 1模型表格(研究) 2表单(带有ModelChoiceField的表单(queryset = TableX.objects.all())

创建一个classView来管理get和post动作。(验证表格也是如此) 在后期程序中,我使用" transaction"避免"假"数据

我希望有人会发布一个复杂的m2m关系的例子。

此致

CINZIA