gpt4 book ai didi

python - Django 管理站点使用外键将两个模型合并为 1 个模型

转载 作者:太空宇宙 更新时间:2023-11-03 20:13:56 24 4
gpt4 key购买 nike

我有这张表 StudentProfile

StudentProfile

和表StudentEnrollmentRecord,我只想在Student User之前添加一列,如下图所示,

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_lated,这样它就不会查询数据库的每一行。

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

关于python - Django 管理站点使用外键将两个模型合并为 1 个模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58569214/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com