所以我有一个带有多个外键字段的模型
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)
我想在此模型中创建一条记录,所以我该如何在函数视图中创建记录
**编辑我尝试了此功能,但是没有起作用
@require_POST
def setInstructor(request):
staff = Staffs.objects.get(admission_number='16259').pk
role = Roles.objects.get(pk=1).pk
curriculum = Curricula.objects.get(pk=1).pk
designation = Designations(staff=staff, role=role, curriculum=curriculum)
designation.save()
return redirect('index'))
答案 0 :(得分:0)
首先,最好将模型命名为 Designation ,因为在verbose_name_plural
中已经有Meta
。
这是您添加新的指定记录的方式。
在views.py
内部,
from my_app.models import Designation
def my_view(request):
# do some stuff
designation = Designation.objects.create(
curriculum = <your_curriculum>,
role = <your_role>,
staff = <your_staff>
)
# do some other stuff
答案 1 :(得分:0)
尝试一下:
@require_POST
def setInstructor(request):
staff = Staffs.objects.get(admission_number='16259')
role = Roles.objects.first()
curriculum = Curricula.objects.first()
if not role or not curriculum:
from django.shortcuts import Http404
raise Http404('role or curriculum not found')
Designations(staff=staff, role=role, curriculum=curriculum).save()
return redirect('index')