gpt4 book ai didi

python - Django with MySQL : OperationalError (1054, "Unknown column ' ' in 'where clause' ") 当试图查询多对多关系时

转载 作者:太空宇宙 更新时间:2023-11-03 11:32:48 25 4
gpt4 key购买 nike

我意识到以前有很多标题相似的问题,但是它们的上下文不同。我一直无法找到与 Django 和我的特殊情况相关的答案。

我在 Django 中的两个模型之间存在多对多关系,如下所示:

class User(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key=True)

def __unicode__(self):
return self.user.username

class Course(models.Model):
users = models.ManyToManyField(User, through='UsersTakeCourses')
title = models.CharField(max_length = 128)
description = models.CharField(max_length = 1024)

def __str__(self):
return self.title

class UsersTakeCourses(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
course = models.ForeignKey(Course, on_delete=models.CASCADE)
mark = models.IntegerField()

在 Django 的 views.py 中,给定一个用户名,我想查询数据库以检索特定用户正在学习的所有类(class)。这是我的查看方法:

def my_courses(request, user_name):
current_user = User.objects.get(username=user_name)
current_user_courses = Course.objects.filter(users__pk=current_user.pk)

context_dict = {'user_courses': current_user_courses}
return render(request, 'FAProject_app/my_courses.html', context_dict)

但是,当我运行服务器并尝试加载与此 View 相关的页面时,我收到以下错误消息:

OperationalError at /firstaid/my-courses/testuser/ (1054, "Unknown column 'FAProject_app_userstakecourses.user_id' in 'where clause'")

我意识到这可能是 mySQL 查询中的一个语法错误,但是我不知道当 Django 自己构建查询时会发生这种情况。

非常感谢任何帮助。

最佳答案

问题在这里

current_user_courses = Course.objects.filter(users__pk=current_user.pk)

试试看

[旧]

current_user_courses = Course.objects.filter(users__in=[current_user]) 

[现在]

current_user_courses = Course.objects.filter(users__user=current_user) 

因为在多对多关系中,这会创建新的映射表并且没有直接的多对多字段。

关于python - Django with MySQL : OperationalError (1054, "Unknown column ' ' in 'where clause' ") 当试图查询多对多关系时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48414401/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com