Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter a ListView output based on ID from current URL

My project a shopping list. I have two models: ShoppingList and ShoppingItem like this:

models.py

class ShoppingItem (Model):
    name = models.CharField(max_length=50, null=False)
    count = models.IntegerField(null=False)
    list = models.ForeignKey(ShoppingList, on_delete=models.CASCADE, related_name='shopping_items')
    date_created = models.DateTimeField(auto_now_add=True)

urls.py

urlpatterns = [
    path('ListDetails/<int:pk>', views.ListDetailUpdateView.as_view(), name='listdetailupdate'),
]

views.py

class ListDetailUpdateView(ListView):
    model = ShoppingItem
    template_name = 'xlist_app/ListDetailUpdateView.html'
    context_object_name = 'products'
    queryset = ShoppingItem.objects.filter(list = XXXX)

I need function that return part of url but inside ListView(where"XXXX")

My idea is to cut last part of url (for example when i enter list number 2 i have address http://127.0.0.1:8000/ListDetails/2) and replace "XXXX" with such a function.

In my mind it should look like:

queryset = ShoppingItem.objects.filter(list = int(request.path.split('/')[-1])

if there is a better way to do that i will aprreciate all sugestions

like image 220
Pladq Avatar asked Oct 30 '25 07:10

Pladq


1 Answers

Something like that

class ListDetailUpdateView(ListView):
    model = ShoppingItem
    template_name = 'xlist_app/ListDetailUpdateView.html'
    context_object_name = 'products'

    def get_queryset(self):
       return ShoppingItem.objects.filter(list=self.request.resolver_match.kwargs['pk'])
like image 194
Anton Pomieshchenko Avatar answered Oct 31 '25 20:10

Anton Pomieshchenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!