Django 管理员“是一个”关系
我在 Django 方面有丰富的经验,但我对管理应用程序非常陌生(我们通常根据项目要求将所有内容构建到页面中)。
但现在我正在开发一个需要一些管理工作的项目,而我却被困在一个部分上。
假设我有数据库模型 - 人员、学生、教师
教师和学生都是一个人(可以这么说,他们继承了这些属性)。我如何在管理视图中显示它?
这样,当有人单击添加学生时,他们只会填写学生属性,而且还会填写同一页面上的人员模型所需的属性。这可能吗?
这是模型,还有教员,但与学生类似
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(models.Model):
year = models.CharField(max_length=10)
stud_id = models.IntegerField()
person = models.ForeignKey(Person)
#many to many
任何想法或进一步的问题都会很棒!
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)
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
InlineModelAdmin 就是你的答案!
一探究竟!
这是您需要的代码:
InlineModelAdmin is your answer!
check it out!
Here is the code you need:
另一种方法是使用 Django 模型继承,如下所示:
这样,在学生管理页面中,您将从
Student
和Person
获取所有字段,而无需Inlines
。此外,Django 将自动处理两个表之间的外键。有关模型继承的文档。
Another way is to use Django model inheritance like this:
This way, in the Student Admin page, you will get all the fields from
Student
AND fromPerson
withoutInlines
. Also Django will deal automatically with the ForeignKey between the 2 tables.Docs on Model inheritance.