简体   繁体   中英

How to fetch from the sql table with flask/python

I am trying to implement the search

sql table

id,name,product
1,a,Books
2,b,Books
3,c,Balls,Books,Pen
4,d,Balls,Pen

Fetching from id field which is working fine

if (id): 
         cursor.execute("select * from books where id = %s", [id])
         conn = cursor.fetchall()

How to fetch from the product field dynamically

if (product): 
         cursor.execute("select * from books where product like ('Books')
         conn = cursor.fetchall()

This will print all the 4 rows since Books contain all the rows

if (product): 
         cursor.execute("select * from books where product like ('Balls','Pen')
         conn = cursor.fetchall()

This will print 3rd and 4th row as 3 and 4 have Balls and Pen. After like column it may vary to any number of fields, how to populate it?

It's quite easy, just Use the table name you have created in model add objects and call method all() it's done.

Example:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM