简体   繁体   中英

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. 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.

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 . Just install this library and change the Teacher_Mgmt to the following code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM