0

我正在尝试基于 Django 文档应用基本模型继承。最终目标是在 get_date_info 视图中访问 Exam 和 Date 模型的共享 ID,该视图在 get_exam_info 视图之后调用。也许有比模型继承更好的方法来做到这一点,但这对我来说似乎是最直接的。

这是相关的模型代码:

class Exam(models.Model):
    instructor_first_name = models.CharField(max_length=30)
    instructor_last_name = models.CharField(max_length=30)
    department = models.CharField(max_length=30, null=True)
    course_name = models.CharField(max_length=30, null=True)
    course_number = models.IntegerField(null=True)
    section_number = models.IntegerField(null=True)
    num_students = models.IntegerField(null=True)
    calculator = models.CharField(max_length=30, blank=True)
    notes = models.CharField(max_length=30, blank=True)
    computer_exam = models.BooleanField(default=False)
    scantron = models.BooleanField(default=False)
    timed = models.BooleanField(default=False)
    dictionary = models.BooleanField(default=False)
    comment = models.CharField(max_length=300, blank=True)

class Date(Exam):
    start_date = models.DateField()
    end_date = models.DateField()
    late_start_date = models.DateField(blank=True, null=True)
    late_end_date = models.DateField(blank=True, null=True)

这是相关的视图代码:

def get_exam_info(request):
    if request.method == 'POST':
        exam_form = ExamForm(request.POST)
        if exam_form.is_valid():
            exam_form.save()

            date_form = DateForm()
            return render(request, 'date_info.html', {'date_form': date_form})
    else:
        exam_form = ExamForm()

    return render(request, 'exam_info.html', {'exam_form': exam_form})

def get_date_info(request):
    exam_request = Exam.objects.all()

    if request.method == 'POST':
        date_instance = Date()
        date_form = DateForm(request.POST, instance=date_instance)
        if date_form.is_valid():
            date_form.save()

            current_user_id = date_instance.exam_ptr_id
            print(current_user_id)

            return HttpResponseRedirect('/')

    else:
        date_form = DateForm()

    return render(request, 'date_info.html', {'date_form': date_form})

这是数据库中的结果: 这是考试表

这是日期表

我尝试了其他一些事情:我创建了一个包含共享 id 的抽象模型,然后我创建了这个抽象超类的 Exam 和 Date 类的子类。这在数据库中给出了预期的行为,但随后视图中的考试实例不可用。我还尝试了许多创建 OneToOneFields 以链接 Exam 和 Date 模型的组合,但这些都没有提供所需的行为。

很长一段时间以来,我一直试图弄清楚为什么会发生这种情况。任何帮助,将不胜感激!

4

0 回答 0