朋友先谢谢您的帮助。我想让依赖于父对象的内联并在django admin中借助filter
限制inline内的queryset,我试图确保在admin中内联被异步加载(即,无需重新加载页面或保存页面)面板的更改表格。
admin.py
class AttendanceRecordInline(admin.TabularInline):
model = AttendanceRecord
@admin.register(Level)
class LevelAdmin(admin.ModelAdmin):
pass
@admin.register(Student)
class StudentAdmin(admin.ModelAdmin):
pass
@admin.register(Attendance)
class AttendanceAdmin(admin.ModelAdmin):
inlines = [
AttendanceRecordInline,
]
models.py
class Level(models.Model):
name = models.CharField(max_length=255, null=True, blank=True)
def __str__(self):
return self.name
class Student(models.Model):
name = models.CharField(max_length=255, null=True, blank=True)
level = models.ForeignKey(Level, on_delete=models.CASCADE)
def __str__(self):
return self.name
class Attendance(models.Model):
level = models.ForeignKey(Level, on_delete=models.CASCADE)
date = models.DateTimeField(default=datetime.now)
def __str__(self):
return "Attendance of {}-{}".format(self.level, self.date.strftime('%B %d, %Y'))
class AttendanceRecord(models.Model):
attendance = models.ForeignKey(Attendance, on_delete=models.CASCADE)
student = models.ForeignKey(Student, on_delete=models.CASCADE)
status = models.CharField(max_length=30, choices=ATTENDANCE_STATUS)
def __str__(self):
return "{}-{}-{}".format(self.attendance.date.strftime('%Y-%m-%d'), self.student, self.status)
一些发现:
form, event listener and template
def formfield_for_foreignkey(self, db_field, request, **kwargs):
,它可以工作,但结果不同步覆盖其他功能,结果不同步
get_formset
get_formsets_with_inlines
get_inline_instances
结论: 该发现中的第一个似乎适用于我的情况。用ajax创建foreignkey字段是一种好习惯吗?