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

时间:2019-11-30 22:05:28

标签: 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()

上面的方法可行,但是我找不到在不将用户标识硬编码到用户变量中的情况下将用户标识传递给查询的方法。

模板:

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

{% if user.is_authenticated %}

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

{% endfor %}

1 个答案:

答案 0 :(得分:0)

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 %}