通过登录用户从数据库过滤数据 [英] filtering data from db by logged in user

查看:54
本文介绍了通过登录用户从数据库过滤数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为数据编写查询集,结果必须是该特定用户的对象列表.(已登录用户)

I'm writing a queryset for data and result needs to be list of objects of that particular user. (logged in user)

这是我到目前为止所得到的:

This is what I've got so far:

class List(ListView):

    def get_queryset(self):
        qry =  House.objects.filter(user__user_id=self.request.user).all()
        return qry

models.py:

models.py:

from django.contrib.auth.models import User

class House(models.Model):


    user_id = models.ForeignKey(User, on_delete=models.CASCADE)
    ...
    ...

我怀疑过滤条件很错误,因为回溯显示没有这样的现场用户

I suspect that the very filtering condition is wrong because the traceback says no such field user

我该怎么解决?

推荐答案

您在这里遇到了几个问题:

You have a couple of issues here:

qry =  House.objects.filter(user__user_id=self.request.user).all()

正在将用户ID与用户对象(即不是用户ID)进行匹配.您想要的是:

Is matching a user id, with a User object (i.e. not a user id). What you want is:

qry =  House.objects.filter(user=self.request.user).all()

(这与下一个更改结合在一起)

(This in conjunction with the next change)

在您的 House 模型上,您要指定 user_id .这很令人困惑,因为您实际映射到的是 User 对象.Django当然会使用 id 字段来执行此操作,但是您无需指定它.将到外键的映射定义为FK模型的名称(通常是小写,因为这是字段名),这是更正常的做法.

On Your House model, you're specifying user_id. This is confusing because what you are actually mapping to is the User object. Django will of course use the id field to do this, but you don't need to specify it. It is more normal to define your mapping to a foreign key as the name of the FK model (only in lower case, obviously, as it's a field name).

user = models.ForeignKey(User, on_delete=models.CASCADE)

这篇关于通过登录用户从数据库过滤数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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