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

不打扰是莪最后的温柔 提交于 2020-07-03 09:28:05

问题


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. But, I want to get the blog_id of all the matching rows that I just query with c.fetchall().

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):

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:

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:

    <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.


回答1:


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]




回答2:


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:

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!



来源:https://stackoverflow.com/questions/61886605/how-can-i-get-the-blog-id-of-the-rows-of-the-sqlite-table-i-just-query-and-used

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!