Попытка фильтрации данных на основе набора дочерних моделей Django
Пытаюсь создать функцию на основе, где исполнитель получает варианты на основе пинкодов. Пробовал этот метод, но ничего не получается, может кто-нибудь может помочь? Заранее спасибо... (Не судите за код, потому что это ранняя стадия разработки и я начинающий разработчик, так что извините, если код плохо читается)
Models.py
views.py
class excutive_home_page(View):
@login_required(login_url='login')
def get(self, *args, **kwargs):
current_user=request.user
str_current_user=str(current_user.id)
if current_user:
get_excutive=ExcutiveRegistration.objects.filter(pk=str_current_user)
str_get_excutive=str(get_excutive)
get_excutive_pincode=ExcutiveRegistrationPincode.objects.filter(pk=str_get_excutive)
str_get_excutive_pincode=str(get_excutive_pincode)
customers = Customer.objects.filter(Pincodes=str_get_excutive_pincode)
context = {
"customers":customers,
}
return render(self.request, 'excutive\excutive_home_page.html', context)
return HttpResponse(self.request, "try someother way")
excutive_home_page.html
hi {{request.user}}
{% for customer in customers %}
{{customer}}
Вам нужно получить Covering_Pincode
из ExcutiveRegistrationPincode
s, а не использовать str(…)
. Но используя IntegerField
s вместо просто ForeignKey
s, вы усложняете запрос, и не можете эффективно использовать Django ORM.
Вы также можете упростить работу, используя TemplateView
[Django-doc]:
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import TemplateView
class ExcutiveHomeView(LoginRequiredMixin, TemplateView):
template_name = 'excutive/excutive_home_page.html'
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
pincodes = [
e.Covering_Pincode
for e in ExcutiveRegistrationPincode.objects.filter(
ExcutiveRegistration__user=request.user
).only('Covering_Pincode')
]
context['customers'] = Customer.objects.filter(Pincodes__in=pincodes)
return context
или даже лучше с простым ListView
[Django-doc]:
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import ListView
class ExcutiveHomeView(LoginRequiredMixin, ListView):
context_object_name = 'customers'
template_name = 'excutive/excutive_home_page.html'
def get_queryset(self, *args, **kwargs):
pincodes = [
e.Covering_Pincode
for e in ExcutiveRegistrationPincode.objects.filter(
ExcutiveRegistration__user=request.user
).only('Covering_Pincode')
]
return Customer.objects.filter(Pincodes__in=pincodes)