简体   繁体   中英

Django loop through model choices

This is the base code I am using:

https://github.com/justdjango/video-membership/tree/master/courses

3 main files:

  1. models.py
  2. views.py
  3. templates/course_list.html

But I added some more functionality to models.py to include a skill_level and subject with model choices:

class Subject(models.Model):
    SUBJECT_CHOICES = (
        ('tech', 'Technical'),
        ('bus', 'Business'),
        ('lead', 'Leadership'),
    )
    name = models.CharField(max_length=20,choices=SUBJECT_CHOICES, unique=True)

    def __str__(self):
        return self.name

class Skill_level(models.Model):
    SKILL_LEVEL_CHOICES = (
        ('Begin', 'Beginner'),
        ('Interm', 'Intermediate'),
        ('Adv', 'Advanced'),
    )
    name = models.CharField(max_length=20,choices=SKILL_LEVEL_CHOICES, unique=True)

    def __str__(self):
        return self.name

class Course(models.Model):
    slug = models.SlugField()
    title = models.CharField(max_length=120)
    description = models.TextField()
    allowed_memberships = models.ManyToManyField(Membership)
    created_at = models.DateTimeField(auto_now_add=True)
    subjects = models.ManyToManyField(Subject)
    skill_level = models.ManyToManyField(Skill_level)
    visited_times = models.IntegerField(default=0)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('courses:detail', kwargs={'slug': self.slug})

    @property
    def lessons(self):
        return self.lesson_set.all().order_by('position')

What I want to eventually do is to loop through the subjects and skill_levels so that the loop results could be used in a dropdown menu so users could search/filter for courses of a certain subject or courses of a certain skill level. But for right now I want to get the dropdown form populated with the choices.

Example Outcome:

https://imgur.com/a/YKhORP9

I would appreciate if someone could provide some code that could accomplish this.

class Skill_level(models.Model):
    choices = models.CharField(max_length=25)

    def __str__(self):
        return self.choices

class Course(models.Model):
    skill_level = models.ForeignKey(Skill_level, on_delete= ....)

You can try this way, it will show as drop down in your form.

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