問題

我有這個表StudentProfile

StudentProfile

和表StudentEnrollmentRecord,我只想在學生使用者之前新增一個列,就像下面的圖片一樣,

enter image description here

這是我在model.py中的程式碼

 class StudentProfile(models.Model):
   LRN = models.CharField(max_length=500,null=True)
   Firstname = models.CharField(max_length=500,null=True,blank=True)
   Middle_Initial = models.CharField(max_length=500,null=True,blank=True)
   Lastname = models.CharField(max_length=500,null=True,blank=True)

class StudentsEnrollmentRecord(models.Model):
    Student_Users = models.ForeignKey(StudentProfile, related_name='+', on_delete=models.CASCADE,null=True)
    School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True)
    Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True)
    Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True,blank=True)
    Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, null=True)
    Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE,blank=True,null=True)
 

這是我在admin.py中的程式碼

 class StudentsEnrollmentRecordAdmin(admin.ModelAdmin):
    list_display = ('Student_Users', 'School_Year', 'Courses', 'Section', 'Payment_Type', 'Education_Levels')
    ordering = ('Education_Levels',)
    list_filter = ('Education_Levels','Section','Student_Users')
 

  最佳答案

您需要在Admin類中定義一個單獨的函式,以從相關物件中檢索列:

 class StudentsEnrollmentRecordAdmin(admin.ModelAdmin):
    ...
    def lrn(self, obj):
        return obj.Student_Users.lrn
 

然後在list_display中使用它

 list_display = ('lrn', ...)
 

我還建議使用list_select_related,所以它不會查詢每行的資料庫.

 class StudentsEnrollmentRecordAdmin(admin.ModelAdmin):
    ...
    list_select_related = ('Student_Users')
 

  相同標籤的其他問題

django