因此,我基本上有一个名为“指定”的模型,它从其他3个模型(课程、角色和人员)派生外键,我正在尝试将一个新记录保存到“指定”模型中,下面的代码显示了“指定”和“人员”模型。但是,对于课程和角色模型,我将不显示,因为您可以假设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)
我已经做了一个决定表单.py获取录取号码(员工模型中的字段)
class AssignRolesForm(forms.Form):
admission_no = forms.CharField(max_length=40,
widget=forms.TextInput(
attrs={'class': 'form-control', 'aria-describedby': 'add-btn'}))
假设当我提交表格时,我想将表格中输入的录取号码引用到员工模型中,然后将其PK保存到名称中的员工字段中,然后如上所述,课程和角色字段引用各自模型的PK 1。我将如何在中编写函数视图.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')
重写窗体上的clean函数可能是您希望将逻辑放在的地方。django文档有一个很好的例子: https://docs.djangoproject.com/en/2.0/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other
相关问题 更多 >
编程相关推荐