python - Django 使用自定义 SQL 而不是模型将 JSON 对象返回到模板

标签 python mysql json django

我目前能够从我的 models.py 和 MySQL 数据库中检索 JSON 数据/对象,并将该 JSON 对象发送到我的模板。我如何才能使用自定义 SQL 从 MySQL 检索数据,然后将其转换为 JSON 对象以发送到我的模板。我基本上根本不想使用 models.py。这是我在使用 models.py 时 views.py 中的内容:

def startpage(request):
    platforms = Platform.objects.select_related().values('platformtype')
    return render(request, 'HTML1.html', {'platforms_as_json' : json.dumps(list(platforms)),})

这是我目前所拥有的:

def my_custom_sql(self):
    cursor = connection.cursor()
    cursor.execute("SELECT platformtype FROM Platform", [self.Platform])
    row = cursor.fetchone()
    return row

除了不使用 models.py 和在我的 View 中使用自定义 SQL 查询之外,我如何能够做同样的事情?谢谢

更新:

def startpage(request):
    platforms = my_custom_sql()
    return render(request, 'Html1.html', {'platforms_as_json' : json.dumps(list(platforms)), })


def my_custom_sql():
    cursor = connection.cursor()
    cursor.execute("SELECT HWPlatformName FROM hwplatform", None)
    rows = cursor.fetchall()
    return rows

现在我可以将数据放到我的模板中,但我不相信它会给我正确的 JSON 格式..

最佳答案

如果你想要模型的实例,你正在寻找 raw对象属性上的方法。

platforms = Platform.objects.raw('SELECT * FROM Platform')

如果您只是从服务器中查找内容,那么您可以只从 SQL 查询中返回值:

platforms = my_custom_sql() # Or call my_custom_sql statically.

如果您正在寻找延迟填充,您可以将 yield 语句放入您的 my_custom_sql 函数中。

关于python - Django 使用自定义 SQL 而不是模型将 JSON 对象返回到模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38705147/

相关文章:

python - 简单的 mod_rewrite 示例

mysql - MSSQL 和 MYSQL 迁移

java - JSON 简单的意外字符?

angularjs - JSON 树 MongoDB

python - 将数据文件解析为二维数组

python - 如何使用opencv丢弃图像的边缘?

python - 如何在python的graphql查询中修复 'parse error on (VAR_SIGN)'

mysql - Spring JPA + MySQL - Hibernate 无法完成架构更新

php - 如果一个失败,如何在 PHP 中处理多个 MySQL 操作

c# - 从 MVC 应用程序中的预编译类序列化 JSON 对象