我目前能够从我的 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/