Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django filtering by user id in Class based ListView

I have a class based ListView of which I would like to filter the objects by the logged in user_id since Item model has a foreign key to settings.AUTH_USER_MODEL

class ItemListView(LoginRequiredMixin, StaffRequiredMixin, ListView):
  model = Item
  template_name = "items/list_items.html"

In function based views I can do this using request.user but not in generic Class based views. Any ideas of how to best do this?

Here is the Item model

class Item(models.Model):
  user = models.ForeignKey(settings.AUTH_USER_MODEL)
  description = models.CharField(max_length=300)
like image 600
chris praka Avatar asked Jul 20 '16 02:07

chris praka


1 Answers

You can override get_queryset function in ListView and filter on self.request.user

def get_queryset(self):
    return Item.objects.filter(user=self.request.user)
like image 66
Eska Avatar answered Nov 17 '22 05:11

Eska