django:manytomanyfield如何通过管理员出现?

时间:2011-05-10 09:15:37

标签: django django-models django-admin

如标题中所述,管理网站中manytomanyfieldthrough的关系如何?

class SchoolClass(models.Model):
    id = models.AutoField(primary_key = True)
    class_name = models.TextField()
    level = models.IntegerField()
    taught_by = models.ManyToManyField(User,related_name="teacher_teaching",through='TeachSubject')
    attended_by = models.ManyToManyField(User,related_name='student_attending')

    def __unicode__(self):
        return self.class_name
    class Meta:
        db_table = 'classes'


class TeachSubject(models.Model):
    teacher = models.ForeignKey(User)
    class_id  = models.ForeignKey(SchoolClass)
    subject = models.ForeignKey(Subject)

在管理网站中,对于模型SchoolClass,我有一个用于上学的领域,但不是老师。

1 个答案:

答案 0 :(得分:55)

您应该使用InlineModelAdminDocs

class TeachSubjectInline(admin.TabularInline):
    model = TeachSubject
    extra = 2 # how many rows to show

class SchoolClassAdmin(admin.ModelAdmin):
    inlines = (TeachSubjectInline,)

admin.site.register(SchoolClass, SchoolClassAdmin)