【问题标题】:Problem with referencing auth_user table in Django with raw query使用原始查询在 Django 中引用 auth_user 表的问题
【发布时间】:2021-10-29 22:52:20
【问题描述】:

我需要在我的表上进行内部联接,并且我需要将auth_user 表中的用户姓氏和名字添加到项目中。项目收集在另一个表 (Project) 中,该表连接到 Profile 模型,我使用该模型扩展了我的 User 模型。

但我使用的是 SqLite3,所以我编写了一个在 SqLite Viewer 中运行良好的查询:

SELECT last_name, first_name, projekt_id 
FROM 'auth_user' 
INNER JOIN stressz_profile ON 
stressz_profile.user_id = auth_user.id 
WHERE projekt_id=1 

我对 Django 的查询是这样的:

resztvevok = Profile.objects.raw('SELECT username, projekt_id FROM auth_user AS resztvevok INNER JOIN stressz_profile ON stressz_profile.user_id = auth_user.id WHERE projekt_id=1')

但是当我刷新浏览器时,它会说:

no such column: auth_user.id

models.py

class Profile(models.Model):

    def __str__(self):
        return str(self.user)

    user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
    projekt = models.ForeignKey(Projekt, on_delete=models.CASCADE, default=3)
    ... 

【问题讨论】:

    标签: python sql django sqlite


    【解决方案1】:

    您正在从 auth_user 表中检索数据,但引用的是 Profile 类模型实例。我想一定是User.objects.raw(...)

    【讨论】:

      【解决方案2】:

      我认为问题在于您在访问id 列时没有使用别名resztvevok

      resztvevok = Profile.objects.raw('SELECT username, projekt_id FROM auth_user AS resztvevok INNER JOIN stressz_profile ON resztvevok.id = stressz_profile.user_id WHERE projekt_id=1')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-06-16
        • 1970-01-01
        • 2012-03-13
        • 1970-01-01
        • 1970-01-01
        • 2021-09-03
        • 1970-01-01
        • 2017-01-15
        相关资源
        最近更新 更多