【问题标题】:Django: Form and many2many relationship using through relationshiopDjango:表单和many2many关系使用通过关系
【发布时间】:2015-06-27 13:12:35
【问题描述】:

我正在尝试通过规范来解决涉及“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 开始,但我不知道如何显示所涉及的“内联”表单。

提前致谢 C.

【问题讨论】:

    标签: django forms model


    【解决方案1】:

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

    我创建了三个表单。 1 范本(学习) 2 表单(带有ModelChoiceField(queryset=TableX.objects.all())的表单)

    创建了一个 classView 来管理 get 和 post 操作。(也是验证表单) 在 post 过程中,我使用“事务”来避免“假”数据。

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

    问候

    辛齐亚

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多