Answer the question
In order to leave comments, you need to log in
Filtering related models using django-filters?
There are two related models
class Skill(models.Model):
"""Information about an employee's skills."""
LEVELS = (
('basic', 'Basic'),
('intermediate', 'Intermediate'),
('advanced', 'Advanced'),
('expert', 'Expert'),
)
YEAR_CHOICES = []
for r in range(1, 11):
YEAR_CHOICES.append((r, r))
employee = models.ForeignKey(
Employee, on_delete=models.CASCADE, related_name="employee_skills")
technology = models.ForeignKey(Technology, on_delete=models.CASCADE)
year = models.IntegerField(verbose_name='Duration of technology use (years)', choices=YEAR_CHOICES, default=1)
level = models.CharField("level", max_length=64, choices=LEVELS)
def __str__(self):
return '{} is {} in {}'.format(
self.employee.full_name, self.level, self.technology.name)
class Project(models.Model):
"""Project information."""
name = models.CharField("project name", max_length=64)
description = models.TextField("project description")
technologies = models.ManyToManyField(
Technology, verbose_name="technologies used on the project")
def __str__(self):
return self.name
class EmployeeFilter(django_filters.FilterSet):
skills = django_filters.ModelChoiceFilter(queryset=Technology.objects.all())
class Meta:
model = Employee
fields = ['skills']
<form method="get">
<div class="card-body">
<div class="row">
<div class="form-group w-100">
<label for="skills">Technology</label>
{% render_field filter.form.skills class="form-control bg-light" %}
</div>
</div>
<button type="submit" class="btn btn-warning">
<span ><i class="fas fa-search"></i></span> Search
</button>
<button type="button" class="btn btn-secondary"><span ><i class="fas fa-recycle fa-fw"></i></i></span><a href="{% url 'account_list' %}" class="text-white">Clear</a></button>
</div>
</form>
class Employee(models.Model):
"""Employee information."""
user = models.OneToOneField(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='employee')
skills = models.ManyToManyField(
Technology, through="Skill", verbose_name="skills", blank=True)
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question