python - 如何使用flask/python从sql表中获取
问题描述
我正在尝试实现搜索
sql表
id,name,product
1,a,Books
2,b,Books
3,c,Balls,Books,Pen
4,d,Balls,Pen
id
从工作正常的字段中获取
if (id):
cursor.execute("select * from books where id = %s", [id])
conn = cursor.fetchall()
如何product
动态从字段中获取
if (product):
cursor.execute("select * from books where product like ('Books')
conn = cursor.fetchall()
这将打印所有 4 行,因为 Books 包含所有行
if (product):
cursor.execute("select * from books where product like ('Balls','Pen')
conn = cursor.fetchall()
这将打印第 3 行和第 4 行,因为 3 和 4 有 Balls 和 Pen。在like 列之后,它可能会改变为任意数量的字段,如何填充它?
解决方案
这很简单,只需使用您在模型添加对象中创建的表名并调用方法all()
就完成了。
例子:
class Student(models.Model):
name = models.CharField(max_length=100)
def index(request):
if request.method == "GET":
data = Student.objects.all()
return render('index.html', data)
推荐阅读
- python - 在 Python 中按时间范围对数据进行分组
- php - 当表单在单独的树枝中呈现时如何访问表单输入?
- phaser-framework - 将图像从 JS 加载到 Phaser 游戏
- javascript - ngRx 操作未正确分派
- c++ - 我的程序没有从文件中读取并输入数据
- graph-databases - 如何对 CMS 的图形数据库中节点的访问权限进行最佳建模
- javascript - 制作具有firestore和云功能的跟随系统
- python - 如何修复此函数语法?
- python - 如何使用贝叶斯优化(在 Python 中)在超参数空间上调整超参数?
- flutter - 如何在数字增加时对其进行动画处理