简体   繁体   中英

Django Match Model Choice Field to Foreignkey

I'm trying to make a Quiz App for my College... I want to map every department to a Faculty

models.py

Class Faculty(models.Model):
    faculty_choice = [
        ("FOE","faculty of engineering"),
        ("FOS","faculty of science"),
        ("FOA","faculty of Agriculture"),
    ]

    faculty = models.CharField(
        max_length=3,
        choices=faculty_choice,
        default=FOE,
    )

Class Department(models.Model):
    Faculty = models.FOREIGNKEY( Faculty, on_delete=CASCADE)
    #this is where my problem is I don't know the next step

Under the Faculty of engineering we have other options to

Like

Faculty Of Engineering

  1. Mechanical
  2. Electrical
  3. Civil

Faculty Of Science

  1. Mathematics
  2. Physics
  3. Chemistry

Faculty Of Agriculture

  1. Animal
  2. Plants
  3. Economy and extension

hope my question is descriptive enough❓

You are doing everything correct, just create department_name in your Department model:

faculty_choice = [
        ("FOE", "faculty of engineering"),
        ("FOS", "faculty of science"),
        ("FOA", "faculty of Agriculture"),
    ]


class Faculty(models.Model):
    faculty_name = models.CharField(choices=faculty_choice, default='FOE')


class Department(models.Model):
    department_name = models.CharField(max_length=150)
    faculty = models.ForeignKey(Faculty, on_delete=models.CASCADE, related_name='departments')

Then you can access department fields using related_name from Faculty class object. Assuming foe is Faculty object, using:

foe.departments.all()

will give you all instances of Department model that have relation with foe

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