Django将新记录保存到具有多个外键的表中

时间:2018-07-15 16:05:40

标签: python django

因此,我基本上有一个名为Designations的模型,该模型从其他3个模型(课程,角色和职员)中派生外键,并且我正尝试将新记录保存到Designations模型中,下面的代码显示了Designations and Staffs模型。但是,对于课程和角色模型,我不会显示,因为您可以假设Curriula中的PK 1,并且角色模型将用作指定模型的课程和角色字段中的数据

class Designations(models.Model):
    designation_id = models.AutoField(primary_key=True)
    curriculum = models.ForeignKey(Curricula, on_delete=models.CASCADE)
    role = models.ForeignKey(Roles, on_delete=models.CASCADE)
    staff = models.ForeignKey(Staffs, on_delete=models.CASCADE)

    class Meta:
        db_table = "arc_designations"
        unique_together = ('curriculum', 'role', 'staff')
        verbose_name_plural = "Designations"
        ordering = ['designation_id']

    def __str__(self):
        return '%s of %s %s (%s)' % (self.role.role_name,
                                     self.curriculum.course_period.course.course_abbreviation,
                                     self.curriculum.module_period.module.module_abbreviation,
                                     self.staff.staff_full_name)

class Staffs(models.Model):
    staff_id = models.AutoField(primary_key=True)
    admission_number = models.CharField(max_length=5,
                                        unique=True,
                                        help_text="Enter 5 digits",
                                        validators=[numeric_only, MinLengthValidator(5)])
    staff_full_name = models.CharField(max_length=70,
                                       help_text="Enter staff's full name",
                                       validators=[letters_only])
    created_by = UserForeignKey(auto_user_add=True,
                                editable=False,
                                related_name="staff_created_by",
                                db_column="created_by")
    created_at = models.DateTimeField(auto_now_add=True,
                                      editable=False)
    updated_by = UserForeignKey(auto_user=True,
                                editable=False,
                                related_name="staff_updated_by",
                                db_column="updated_by")
    updated_at = models.DateTimeField(auto_now=True,
                                      editable=False)
    roles = models.ManyToManyField(Roles, through='Designations')

    class Meta:
        db_table = "arc_staffs"
        verbose_name_plural = "Staffs"
        ordering = ['staff_id']

    def __str__(self):
        return '%s (S%s)' % (self.staff_full_name, self.admission_number)

我已经创建了一个form.py来获取mission_number(在Staffs模型中的字段)

class AssignRolesForm(forms.Form):
    admission_no = forms.CharField(max_length=40,
                                 widget=forms.TextInput(
                                     attrs={'class': 'form-control', 'aria-describedby': 'add-btn'}))

假设我提交表格时,我希望将表格中输入的admission_number引用到Staffs模型中,然后将其PK保存到Designation的Staff字段中,然后如上所述,关于课程和角色字段引用各自模型的PK 1。我将如何在views.py

中编写函数

**编辑 我已经尝试按照建议的方式写出视图,下面是下面的代码,目前我无法测试我的项目,所以现在让我看看它是否正确

@require_POST
def setStaff(request):
    form = AssignRolesForm(request.POST)

    if form.is_valid():
        Designations.staff = Staffs.objects.filter(admission_number=form.cleaned_data['admission_no'])
        Designations.role = Roles.objects.get(pk=1)
        Designations.curriculum = Curricula.objects.get(pk=1)
        Designations.save()

    return redirect('index')

1 个答案:

答案 0 :(得分:0)

您可能想在逻辑上覆盖表单上的clean函数。 django文档有一个很好的例子: https://docs.djangoproject.com/en/2.0/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other