I am trying to filter the associated_portfolios fields object to only those created by the user. Which worked before I tried to add pagination (which is working if I remove the current filter I have for associated_portfolios)
I believe what I need to do is remove:
def associated_portfolios
this is because it seems request is not past with the new setup. Instead, I should use this method https://django-filter.readthedocs.io/en/stable/guide/usage.html#filtering-the-primary-qs
filters.py current; not working after adding pagination
def associated_portfolios(request):
associated_portfolios = Portfolio.objects.filter(user=request.user)
return associated_portfolios.all()
class TradeFilter(django_filters.FilterSet):
associated_portfolios = django_filters.ModelMultipleChoiceFilter(queryset=associated_portfolios)
date_range = django_filters.DateFromToRangeFilter(label='Date Range', field_name='last_entry',
widget=RangeWidget(attrs={'type': 'date'}))
class Meta:
model = Trade
fields = ['status', 'type', 'asset', 'symbol', 'broker', 'patterns', 'associated_portfolios']
filters.py possible solution based on documentation
class TradeFilter(django_filters.FilterSet):
date_range = django_filters.DateFromToRangeFilter(label='Date Range', field_name='last_entry',
widget=RangeWidget(attrs={'type': 'date'}))
class Meta:
model = Trade
fields = ['status', 'type', 'asset', 'symbol', 'broker', 'patterns', 'associated_portfolios']
@property
def qs(self):
parent = super().qs
user = getattr(self.request, 'user', None)
return parent.filter(user=user)
The problem is the is no error message but the objects not created by the user are still showing. Tried probably a dozen + variations of this @property from what I've seen on SOF and the docs but no success yet..
views.py
class FilteredListView(ListView):
filterset_class = None
def get_queryset(self):
# Get the queryset however you usually would. For example:
queryset = super().get_queryset()
# Then use the query parameters and the queryset to
# instantiate a filterset and save it as an attribute
# on the view instance for later.
self.filterset = self.filterset_class(self.request.GET, queryset=queryset)
# Return the filtered queryset
return self.filterset.qs.distinct() #.filter(user=self.request.user).order_by('last_entry')
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
# Pass the filterset to the template - it provides the form.
context['filterset'] = self.filterset_class
return context
# Attempt @ Combining Filter and List View to get: TradeFilteredListView
class TradeFilteredListView(FilteredListView):
model = Trade
filterset_class = TradeFilter
paginate_by = 5
template_name = 'portfolios/trade_filter.html'
Side notes:
- The reason I am using a different view setup is due to pagination which I followed this guide on for setting up pagination with django-filters. https://www.caktusgroup.com/blog/2018/10/18/filtering-and-pagination-django/