I've had plenty of experience in Django but I'm very new to the admin app (we usually build everything into the page as per project requirements).
But now I'm working on a project that requires some admin work and I'm stuck on one part.
Say I have Database models - Person, Student, Faculty
Both Faculty and Student 'is a' Person (they inherit those attributes so to speak). How can I show this in the admin view?
So that when someone clicks to add a student they fill out the student only attributes, but also the attributes required the Person model on the same page. Is this possible?
Here's the models, there's also Faculty but it's similar to Student
class Person(models.Model):
last_name = models.CharField(max_length=50)
first_name = models.CharField(max_length=50开发者_StackOverflow中文版)
mi = models.CharField(max_length=50)
phone = models.CharField(max_length=20)
cell = models.CharField(max_length=20)
class Student(models.Model):
year = models.CharField(max_length=10)
stud_id = models.IntegerField()
person = models.ForeignKey(Person)
#many to many
Any ideas or further questions would be awesome!
InlineModelAdmin is your answer! check it out!
Here is the code you need:
class StudentInline(admin.TabularInline):
model = Student
class PersonAdmin(admin.ModelAdmin):
inlines = [
StudentInline,
]
admin.site.register(Person,PersonAdmin)
Another way is to use Django model inheritance like this:
class Person(models.Model):
last_name = models.CharField(max_length=50)
first_name = models.CharField(max_length=50)
mi = models.CharField(max_length=50)
phone = models.CharField(max_length=20)
cell = models.CharField(max_length=20)
class Student(Person):
year = models.CharField(max_length=10)
stud_id = models.IntegerField()
This way, in the Student Admin page, you will get all the fields from Student
AND from Person
without Inlines
. Also Django will deal automatically with the ForeignKey between the 2 tables.
Docs on Model inheritance.
精彩评论