我正在使用django-filter包,我想知道如何在我的django-filter模型中传递请求用户的ModelChoiceFilter中的queryset
我更新了视图列表,由于某种原因,此init函数没有影响
filters.py
class PresenceDateFilter(django_filters.FilterSet):
work_date = DateTimeFromToRangeFilter(
widget=django_filters.widgets.RangeWidget(
attrs={'type': 'date', 'class': 'form-control'},
))
class Meta:
model = PresenceDetailInfo
fields = ('presence_info__counter_presence',
'work_date',
)
models.py
class PresenceDetailInfo(models.Model):
presence_info = models.ForeignKey(PresenceListInfo, default=None, null=True,
on_delete=models.CASCADE, related_name='details_info')
class PresenceListInfo(models.Model):
counter_presence = models.ForeignKey(CounterParty, default=None, null=True,
on_delete=models.CASCADE)
class CounterParty(models.Model):
counter_user = models.ManyToManyField(User, blank=True, related_name='counter_user')
views.py
class ShowPresenceInfoList(AccessMixin, ListView):
model = PresenceDetailInfo
template_name = 'common/presence_info.html'
context_object_name = 'details_list'
def get_context_data(self, *, object_list=None, **kwargs):
context = super(ShowPresenceInfoList, self).get_context_data(**kwargs)
list_of_dates = PresenceDateFilter(self.request.GET, queryset=self.get_queryset())
context['form'] = list_of_dates.form
context['dates'] = list_of_dates.qs
return context
def get_queryset(self):
current_user = self.request.user
current_counters = CounterParty.objects.filter(counter_user=current_user)
if current_user.is_superuser:
qs = PresenceDetailInfo.objects.all().select_related('presence_info', ).order_by(
'work_date')
else:
qs = PresenceDetailInfo.objects.filter(presence_info__counter_presence__in=current_counters).select_related(
'presence_info', ).order_by('work_date')
word = PresenceDateFilter(self.request.GET, queryset=qs, request=self.request)
return word.qs
2条答案
按热度按时间jaql4c8m1#
可以在类PresenceDateFilter内部的init中传递它
您可以自定义查询,在本例中,它将返回模型中的所有对象,并从request.user中获取用户。
arknldoa2#
您可以修改视图:
然后在类PresenceDateFilter内的init中传递查询集