Я пытаюсь создать форму поиска в моем проекте Django, которая будет фильтровать несколько моделей (3). Она работает для одной модели и дополнительной модели, связанной внешним ключом. Но я не могу объединить разные модели запросов в один get_queryset.
forms.py
class SearchForm(forms.Form):
username=forms.CharField(
label = 'enterprise_id',
required = False
)
skill_name=forms.ModelChoiceField(
queryset=Skill_name.objects,
label='skill_list',
required=False
)
model.py
class EnterpriseID(models.Model):
enterprise_id = models.CharField('enterprise_id',max_length=40,blank=True,default="",)
def __str__(self):
return self.enterprise_id
class Skill_name(models.Model):
skill_name = models.CharField('skill_name',max_length=40,blank=False,null=False,)
def __str__(self):
return '{0}'.format(self.skill_name)
class Skill(models.Model):
enterprise_id = models.ForeignKey(EnterpriseID,verbose_name="enterprise_id",on_delete=models.PROTECT,)
skill_name=models.ForeignKey(Skill_name,verbose_name="skill_name",on_delete=models.PROTECT,)
def __str__(self):
return '{0}'.format(self.enterprise_id)
class Employee(models.Model):
# user = models.OneToOneField(accounts_models.AuthUser, on_delete=models.CASCADE, blank=True)
enterprise_id = models.ForeignKey(EnterpriseID,verbose_name="enterprise_id",on_delete=models.PROTECT,)
join_at = models.DateField('join_at',default="",null=True,blank=True)
def __str__(self):
return '{0}'.format(self.enterprise_id)
views.py
class PersonalInfoSearchView(LoginRequiredMixin,ListView):
model = Employee
template_name = 'personal_info/search_personal_info.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['form'] = SearchForm(self.request.GET)
return context
def get_queryset(self):
form = SearchForm(self.request.GET)
queryset = super().get_queryset()
if form.is_valid():
username = form.cleaned_data['username']
skill_name = form.cleaned_data['skill_name']
if username:
queryset=queryset.filter(enterprise_id__enterprise_id__icontains=username)
if skill_name:
skill_query =Skill.objects.filter(skill_name=skill_name)
return queryset.distinct()