有两个相关模型
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
filters.py
class EmployeeFilter(django_filters.FilterSet):
skills = django_filters.ModelChoiceFilter(queryset=Technology.objects.all())
class Meta:
model = Employee
fields = ['skills']
template.html
<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)
如何了解“技能”字段的值?我想我应该在 filters.py 上加一个
字段skill__technology__level = django_filters.ModelChoiceFilter(queryset=??????)