简体   繁体   English

如何获取我刚刚查询并使用的 sqlite 表的行的 blog_id? (在 Python 文件中)

[英]How can I get the blog_id of the rows of the sqlite table I just query and used? (In a Python file)

I have the codes below that let users on my website to search for blogs.我有下面的代码,可以让我网站上的用户搜索博客。 With the current, my HTML page will only show a list of data from all the row that has columns that match with the search input.使用当前,我的 HTML 页面将仅显示所有行中具有与搜索输入匹配的列的数据列表。 But, I want to get the blog_id of all the matching rows that I just query with c.fetchall().但是,我想获取我刚刚使用 c.fetchall() 查询的所有匹配行的 blog_id。

How would I do it?我该怎么做? Should I write some codes right after I query data?... I would greatly appreciate if you help me.我应该在查询数据后立即编写一些代码吗?...如果您能帮助我,我将不胜感激。 Also, if possible, could you show me how can I set the codes below to only query those rows that have a column that match the searching data?另外,如果可能的话,您能否告诉我如何将下面的代码设置为仅查询具有与搜索数据匹配的列的那些行? :

many_posts = BlogPost.query.order_by(BlogPost.date.desc()).paginate(page=page, per_page=10)
(These codes above are placed inside the "if request.method == 'POST':")

My codes (Python):我的代码(Python):

import os 
import _sqlite3

MYDIR = os.path.dirname(__file__)
SQLPATH = os.path.join(MYDIR, "..", "data.sqlite")
conn = _sqlite3.connect(SQLPATH, check_same_thread=False)  

c = conn.cursor()

@core.route('/', methods=['GET', 'POST'])
def index():
    # Call a function to later use in creating the template
    form = Blogsearch_form(request.form)

    if request.method == 'POST':
        c.execute("SELECT * FROM blog_post WHERE problem_name LIKE(?)", ('%' + str(form.search.data) + '%',))
        results = c.fetchall()
        page = request.args.get('page', 1, type=int)
        many_posts = BlogPost.query.order_by(BlogPost.date.desc()).paginate(page=page, per_page=10)
        return render_template('blog_search_result.html', results=results, many_posts=many_posts)



    page = request.args.get('page',1,type=int)
    many_posts = BlogPost.query.order_by(BlogPost.date.desc()).paginate(page=page, per_page=10)
    return render_template('index.html', many_posts=many_posts, form=form)

My codes of the BlogPost's database creation:我的 BlogPost 数据库创建代码:

class BlogPost(db.Model):
    __tablename__ = 'blog_post'
    users = db.relationship(User)

    blog_id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer,db.ForeignKey('users.id'), nullable=False) #users.id  is taken from the tablename(users) and id in its table
    date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)  
    problem_name = db.Column(db.String(140), nullable=False)
    text = db.Column(db.Text, nullable=False)
    blog_image = db.Column(db.String(140), nullable=False, server_default='default_blog.jpg')


    def __init__(self, text, problem_name, user_id, blog_image):
        self.text = text
        self.problem_name = problem_name
        self.user_id = user_id
        self.blog_image = blog_image



    def __repr__(self):
        return f"Post ID: {self.post_id} -- Date:{self.date}---{self.problem_name}"

Part of my HTML codes:我的 HTML 代码的一部分:

    <h4>Search results:</h4>
    <h5>{{ results }}</h5>
   <p><small class="text-muted">If you see [ ] as the result, it means Upchanges have no relating problems to your search</small></p>

<div class="container row row-cols-1 row-cols-md-2 text-center">
{% for post in many_posts.items%}

    <div class="card border-dark mb-3 " style="width: 20rem;">
     <div class="card-body ">
         <h7><a class="text-warning" href="{{ url_for('users.user_posts', username=post.creator.first_name+post.creator.middle_name+post.creator.last_name) }}"><img class="text-center rounded" src="{{ url_for('static', filename='profile_pics/'+ post.creator.profile_image) }}" width = "35" height = "35" alt=""> {{ post.creator.first_name}} {{ post.creator.middle_name }} {{ post.creator.last_name }}</a></h7>
         <p></p>
         <img class="text-center rounded responsive1" alt="" src="{{ url_for('static', filename='blog_pics/'+ post.blog_image) }}" width = "495" height = "250">
         {# Need caution for post.blog_image on the code above #}
         <p></p>
         <h2><a class="card-tittle text-body problem" href="{{ url_for('blog_posts.blog_view', blog_validated_id=post.blog_id) }}">{{ post.problem_name[0:40]}}..</a></h2>
         <p class="card-text">{{ post.text[0:100] }}</p>
         <p><small class="text-muted">Posted on: {{ post.date.strftime('%Y-%m-%d') }}</small></p>
         <a class="btn btn-warning" href="{{ url_for('blog_posts.blog_view', blog_validated_id=post.blog_id) }}">Read more</a>
     </div>


    </div>

{% endfor %}


Additionally, all of my current codes are working fine and showing no errors.此外,我当前的所有代码都工作正常并且没有显示错误。

Not sure I understand.不确定我是否理解。 Do you mean something like.你的意思是类似的。

c.execute("SELECT blog_id FROM blog_post WHERE problem_name LIKE(?)", ('%' + str(form.search.data) + '%',))
results = c.fetchall()
blog_ids = [entry[0] for entry in results]

sorry to jump in late but if you want an sqlalchemy solution, then you should do something like below to get the list of ids:抱歉迟到了,但如果您想要 sqlalchemy 解决方案,那么您应该执行以下操作来获取 id 列表:

id_list = [i[0] for i in BlogPost.query.with_entities(BlogPost.blog_id ).filter(BlogPost.problem_name.ilike("%" + form.search.data  + "%")).all()]

Also, I think for security reasons, you should use an ORM rather than the pure SQL Query!另外,我认为出于安全原因,您应该使用 ORM 而不是纯 SQL 查询!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 取决于我刚刚从 sqlite 数据库表中查询的列的值,我如何在 HTML 文件上显示不同的图标? - Depend on the the values of the column I just query from the sqlite database's table, how could I show different icons on my HTML file? 当我有两个具有名为 id 的属性的表时,如何获取 SQLite 查询以返回表的 id? - How do I get a SQLite query to return the id of a table when I have two tables that have an attribute named id? 我如何在python和sqlite中获得价值? - how can i get value ??in python and sqlite django:blog()缺少1个必需的位置参数:&#39;blog_id&#39; - django: blog() missing 1 required positional argument: 'blog_id' 如何使用Python3从sqlite表中删除某些行/行? - How can I delete certain row/rows from sqlite table using Python3? 如何获取刚加入服务器的会员ID? - How can I get the ID of the member who just joined the server? 如何使用python从此xml / txt文件构建sqlite表? - How can I build an sqlite table from this xml/txt file using python? 我只是改变了我的 sqlite 表并通过我的控制台添加了一个列; 如何将此命令添加到我的 Python 文件或迁移文件中? - I just ALTER my sqlite table and added a column through my console; How do I add this command into my Python file or migration file? 如何在 sqlite 查询中插入 Python 变量? - How can I insert a Python variable in a sqlite query? 如何获得Messenger中使用的“竖起”的可点击“id”? - How can I get the Clickable “id” for the “thumbs up” used in messenger?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM