在基于类的ListView中按用户ID进行django过滤 [英] django filtering by user id in Class based ListView

查看:71
本文介绍了在基于类的ListView中按用户ID进行django过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基于类的ListView,我希望通过登录的user_id过滤对象,因为Item模型具有设置的外键.AUTH_USER_MODEL

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"

在基于函数的视图中,我可以使用request.user进行此操作,但不能在基于通用类的视图中进行此操作.关于如何最好地做到这一点的任何想法?

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?

这是商品模型

class Item(models.Model):
  user = models.ForeignKey(settings.AUTH_USER_MODEL)
  description = models.CharField(max_length=300)

推荐答案

您可以在ListView中覆盖get_queryset函数,并在self.request.user上进行过滤

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)

这篇关于在基于类的ListView中按用户ID进行django过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆