관계를 통해서만 액세스 할 수있는 여러 Django 모델의 Charfields를 얻기 위해 Django보기를 작성하는 방법

StackOverflow https://stackoverflow.com/questions/676267

문제

다음 Django 모델을 참조하십시오.

class Student(models.Model):
    reference_num = models.CharField(max_length=50, unique=True)
    name = models.CharField(max_length=50)
    birthdate = models.DateField(null=True, blank=True)
    is_active = models.BooleanField(db_index=True)

class Examination(models.Model):
    short_name = models.CharField(max_length=20, unique=True)
    name = models.CharField(max_length=50, unique=True)
    is_active = models.BooleanField(db_index=True)

class Subject(models.Model):
    short_name = models.CharField(max_length=20, unique=True)
    name = models.CharField(max_length=50, unique=True)
    is_active = models.BooleanField(db_index=True)

class EducationalQualification(models.Model):
    student = models.ForeignKey(Student)
    examination = models.ForeignKey(Examination)
    subject = models.ForeignKey(Subject, null=True, blank=True)
    institution = models.CharField(max_length=50)
    from_date = models.DateField(null=True, blank=True)
    to_date = models.DateField()
    marks = models.DecimalField(max_digits=5, decimal_places=2)

그리드에 주어진 학생에 대한 마지막 모델 "EducationalQualification)를 표시해야합니다 (학생은 여러 교육 자격을 가질 수 있음).

그리드에는 "학생 이름", "짧은 이름의 시험 이름", "주제의 짧은 이름", "EducationalQualification.institution", "EducationalQualification.From_Date", "EducationalQualification.to_date"및 "EducationalQualification.Marks"에 대한 열이 있습니다.

나는이 데이터를 얻기 위해 django 조회수를 내놓을 수 없었습니다 (학생 .pk).

누군가 몇 가지 아이디어로 나를 도와 줄 수 있습니까?

문안 인사.

도움이 되었습니까?

해결책

당신은 모든 것을 가져와야합니다 EducationalQualification 모든 관계 대상이있는 특정 학생을위한 대상 :

def view_qualifications(request, student_id):
    qs = EducationalQualification.objects.filter(student__pk=student_id).\
                           select_related("student", "examination", "subject")
    # ...

그런 다음 템플릿에서 반복을 통과합니다.

{% for q in qs %}
<tr>
   <td>{{q.student.name}}</td>
   <td>{{q.examination.short_name}}</td>
   <td>{{q.subject.short_name}}</td>
   <td>{{q.institution}}</td>
   <td>{{q.from_date}}</td>
   <td>{{q.to_date}}</td>
   <td>{{q.marks}}</td>
</tr>
{% endfor %}

다른 팁

데이터베이스보기와 지정된 모델을 만듭니다 managed = False 메타 클래스에서.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top