У меня есть таблица SQLite, в которой я храню несколько столбцов, 3 из них Product Name
, Description
и Like
. Я хочу, чтобы пользователь имел возможность искать названия продуктов, добавлять данные о продуктах в виде строк в HTML-таблице и нажимать, нравится ли пользователю продукт или нет. Затем следует обновить столбец SQLite Like
для выбранных продуктов.
Как видно из приведенного ниже кода, я пытаюсь получить «имя», введенное пользователем, и отфильтровать SQLite. таблицу для данных и распечатать его в виде таблицы. Но я не знаю, как написать строку, где я фильтрую таблицу SQLite, как отмечено ниже.
app.py
from flask import Flask, request, jsonify, render_template, redirect
import os
from models import db, Products
app = Flask(__name__)
# Create dummy secrey key so we can use sessions
app.config['SECRET_KEY'] = '123456790'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
# Create in-memory database
app.config['DATABASE_FILE'] = 'mna.db'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + app.config['DATABASE_FILE']
db.init_app(app)
@app.route('/', methods = ['GET'])
def index():
products = []
name = request.args.get('search')
products.append(Products.productname == name) ##<-- I don't know how to write this line correctly
return render_template('index.html', products=products)
# run Flask app
if __name__ == "__main__":
app.run(debug = True)
models.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Products(db.Model):
productid= db.Column(db.String(), primary_key=True)
productname= db.Column(db.String(), primary_key=False)
description = db.Column(db.String(), nullable=False)
like = db.Column(db.Boolean(), nullable=False)
def __str__(self):
return unicode(self).encode('utf-8')
def __unicode__(self):
return "Name: {productname}; Description : {description}".format(productname=self.productname, description=self.description)
И мой index.html
{% extends 'base.html' %}
{% block content %}
<form method="GET">
<input type="text" placeholder="Search for Product.." name="search">
<button type="submit"><i class="search-container"></i></button>
</form>
<div class="product-container" style="overflow: auto; max-height: 80vh">
<div class="table-responsive">
<table class="table" id="products">
<thead>
<tr>
<th scope="col">Product Name</th>
<th scope="col">Description</th>
<th scope="col">Like</th>
</tr>
</thead>
<tbody>
{% for product in products %}
<tr ={{ product .productid}}>
<th scope="row">{{ product .productname}}</th>
<td> {{ product.description }} </td>
<td> {{ product.like }} </td>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endblock %}