python - 在 Django 中,如何查询登录用户的 MYSQL 数据库? (即特定用户的结果,无需对用户 ID 进行硬编码)

标签 python mysql django orm

到目前为止,我已经了解了这一点,抱歉,我是编程新手 - 正在尝试学习 Django 和 Python。

查看:

def dashboard(request):
    return render(request, 'app/dashboard.html', {'my_custom_sql': my_custom_sql})

下面的函数不会在模板中输出任何内容

def my_custom_sql(self):
    return self.request.CustomUser.customuser_set.all()

使用硬编码原始 SQL 替代上述方法:

def my_custom_sql():
 current_user = 1
 with connection.cursor() as cursor:
     cursor.execute("SELECT first_name FROM customuser WHERE id = 
     %s",[current_user])
     row = cursor.fetchone()

上面的方法有效,但我找不到一种将用户 ID 传递给查询而不将其硬编码到用户变量中的方法。

模板:

<h3> Displaying User's First Name </h3>

{% if user.is_authenticated %}

    <p>The first name: {{my_custom_sql}}</p>

{% endfor %}

最佳答案

andtmc。欢迎来到SO。

您确实需要关闭 if 标记:

模板

{% if user.is_authenticated %}
    <p>The first name: {{my_custom_sql.first_name}}</p>
{% endif %}

views.py

def dashboard(request):
    return render(request, 'app/dashboard.html', {'my_custom_sql': my_custom_sql(request)})

def my_custom_sql(request):
    return CustomUser.objects.get(pk=request.user.pk)

根据您的型号,您可以:

{% if user.is_authenticated %}
    <p>The first name: {{user.first_name}}</p>
{% endif %}

关于python - 在 Django 中,如何查询登录用户的 MYSQL 数据库? (即特定用户的结果,无需对用户 ID 进行硬编码),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59120687/

相关文章:

python - 可以在 Click 6 中执行多个嵌套命令

python - 如何在 Python 的同一行打印多行字符串

mysql - 更新: You can't specify target table 'table' for update in FROM clause

mysql - 查询以获取一天中基于小时的最多 View

javascript - 为什么CSS和JS不走Django?

python - 如何将脚本作为 Travis CI 构建的一部分运行?

python - QtWebEngine 拦截带有自定义 URL 模式服务回复的请求

php - 如何使用 HTML 链接将变量从一个 PHP 文件传递​​到另一个文件?

django - 如何将变量发送到通用 View 调用的模板

django - Django 应用程序的负载测试