首页 > 解决方案 > 在 Django 中,如何查询登录用户的 MYSQL 数据库?(即特定用户的结果,无需对用户 ID 进行硬编码)

问题描述

到目前为止,我有这个,抱歉我是编程新手 - 试图学习 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()

上面的作品,但我找不到将用户标识传递给查询而不将其硬编码到用户变量中的方法。

模板:

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

{% if user.is_authenticated %}

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

{% endfor %}

标签: pythonmysqldjangoorm

解决方案


和tmc。欢迎来到 SO。

您确实需要关闭if标签:

模板

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

视图.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 %}

推荐阅读