查询两个表的一个表单
Query two tables for a form
我有两个模型:
class Student(models.Model):
student_id = models.BigIntegerField(primary_key=True)
student_lastname = models.CharField(max_length=200)
student_firstname = models.CharField(max_length=200)
student_courseid = models.ForeignKey(Course)
class Course(models.Model):
course_location = models.CharField(max_length=200)
course_begin = models.DateField(blank=True)
course_end = models.DateField(blank=True)
我有一个表格可以显示每个学生的信息。通过 url.
选择学生
urlpatterns = [
# ex: /00116777/detail/
url(r'^(?P<studentid>[0-9]+)/detail/$', StudentDetailView.as_view(), name='detail'),
]
在此表单中,我想添加 course_location,但我不知道如何查询两者,以便我可以在模板中将其用作
<div class="col-md-3 col-lg-2">
<p class="student-detail-data">{{ course.course_location }}</p>
</div>
这是我目前的看法:
class StudentDetailView(DetailView):
model = Student
template_name = "student/detail.html"
slug_field = 'student_id'
slug_url_kwarg = 'studentid'
def get_context_data(self, **kwargs):
context = super(StudentDetailView, self).get_context_data(**kwargs)
data = self.kwargs['studentid']
context['object'] = Student.objects.filter(student_id=data)
return context
如有任何帮助或建议,我们将不胜感激。谢谢!
您可以通过外键在模板中执行 {{ student.student_courseid.course_location }}
并且不需要创建student_id
,Django自动添加pk
.
我不知道,你想要什么样的逻辑,但我认为对于课程和学生,你需要创建 models.ManyToManyField
.
点击特定学生时,它必须显示信息(还有课程详细信息)
所以我想,这会起作用。
{{student.student_courseid.course_loation}} in your html page.
希望这会起作用,因为默认情况下。
我有两个模型:
class Student(models.Model):
student_id = models.BigIntegerField(primary_key=True)
student_lastname = models.CharField(max_length=200)
student_firstname = models.CharField(max_length=200)
student_courseid = models.ForeignKey(Course)
class Course(models.Model):
course_location = models.CharField(max_length=200)
course_begin = models.DateField(blank=True)
course_end = models.DateField(blank=True)
我有一个表格可以显示每个学生的信息。通过 url.
选择学生urlpatterns = [
# ex: /00116777/detail/
url(r'^(?P<studentid>[0-9]+)/detail/$', StudentDetailView.as_view(), name='detail'),
]
在此表单中,我想添加 course_location,但我不知道如何查询两者,以便我可以在模板中将其用作
<div class="col-md-3 col-lg-2">
<p class="student-detail-data">{{ course.course_location }}</p>
</div>
这是我目前的看法:
class StudentDetailView(DetailView):
model = Student
template_name = "student/detail.html"
slug_field = 'student_id'
slug_url_kwarg = 'studentid'
def get_context_data(self, **kwargs):
context = super(StudentDetailView, self).get_context_data(**kwargs)
data = self.kwargs['studentid']
context['object'] = Student.objects.filter(student_id=data)
return context
如有任何帮助或建议,我们将不胜感激。谢谢!
您可以通过外键在模板中执行 {{ student.student_courseid.course_location }}
并且不需要创建student_id
,Django自动添加pk
.
我不知道,你想要什么样的逻辑,但我认为对于课程和学生,你需要创建 models.ManyToManyField
.
点击特定学生时,它必须显示信息(还有课程详细信息)
所以我想,这会起作用。
{{student.student_courseid.course_loation}} in your html page.
希望这会起作用,因为默认情况下。