首页 > 解决方案 > 如何使用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 列之后,它可能会改变为任意数量的字段,如何填充它?

标签: pythonmysqlflask

解决方案


这很简单,只需使用您在模型添加对象中创建的表名并调用方法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)

推荐阅读