[英]How to make a model having two foreign Key relations with the different models
I have made an app in which i have made three models as below: 我制作了一个应用,其中制作了以下三个模型:
from django.db import models
class Class_Mgmt(models.Model):
class_name = models.CharField(max_length=8,null=False,blank=False)
def __str__(self):
return self.class_name
class Section_Mgmt(models.Model):
stu_class=models.ForeignKey(Class_Mgmt)
section_name=models.CharField(max_length=1,null=False,blank=False)
def __str__(self):
return self.section_name
class Teacher_Mgmt(models.Model):
teacher_name=models.CharField(max_length=50,null=False,blank=False)
tea_class=models.ForeignKey(Class_Mgmt)
tea_section=models.ForeignKey(Section_Mgmt)
def __str__(self):
return self.teacher_name
Here, Section_Mgmt
class has a foreignKey relation with Class_Mgmt
that means when i run the project and add a new section_name
, then class_name
will be selected from a drop-down list of all the existing classes. 在这里, Section_Mgmt
类与Class_Mgmt
有一个ForeignKey关系,这意味着当我运行项目并添加新的section_name
,将从所有现有类的下拉列表中选择class_name
。 It is working well in the project. 在该项目中运行良好。 But, in the Teacher_Mgmt
model, i want to do like this: When i enter a new teacher in my form, then when i select the existing class from the dropdown list, then it will only show the sections available on the selected class because, section_Mgmt
model also has the foreign key relation with the class_Mgmt
model. 但是,在Teacher_Mgmt
模型中,我想这样做:当我在表单中输入新老师时,然后从下拉列表中选择现有班级时,它将仅显示所选班级中可用的部分,因为, section_Mgmt
模型也与class_Mgmt
模型具有外键关系。
At present, when i am running the project and enter a new teacher, and select a class from the dropdown showing all the existing classes,then is showing all the sections instead of showing only those sections available in that class. 目前,当我运行该项目并输入新老师,并从显示所有现有班级的下拉列表中选择一个班级时,则将显示所有节,而不是仅显示该班级中可用的那些节。
Django does not have this functionality built in but you can use django-smart-selects . Django没有内置此功能,但是您可以使用django-smart-selects 。 Just install this library and change the Teacher_Mgmt to the following code: 只需安装此库,然后将Teacher_Mgmt更改为以下代码:
from smart_selects.db_fields import ChainedForeignKey
class Teacher_Mgmt(models.Model):
teacher_name=models.CharField(max_length=50,null=False,blank=False)
tea_class=models.ForeignKey(Class_Mgmt)
tea_section=ChainedForeignKey(
Section_Mgmt,
chained_field="tea_class",
chained_model_field="tea_class",
show_all=False,
auto_choose=True
)
def __str__(self):
return self.teacher_name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.