简体   繁体   English

按日期时间列中的日期过滤 flask / SQLalchemy 中的帖子

[英]filtering posts in flask / SQLalchemy by a date in a datetime column

I'm building a website in Flask, and I need to find a way to filter the posts displayed on the page between past and current posts, based on the end_date column.我正在 Flask 中建立一个网站,我需要找到一种方法来根据end_date列在过去和当前帖子之间过滤页面上显示的帖子。 All the current posts would be on one list, and the expired posts would be on another list.所有当前帖子将在一个列表中,过期的帖子将在另一个列表中。

Here is the model这是 model

class Events(db.Model):
    __tablename__="events"
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(45), nullable=False, unique = True)
    start_date = db.Column(db.DateTime, default = datetime.utcnow)
    end_date = db.Column(db.DateTime, nullable = False)
    body = db.Column(db.Text, nullable = False)
    form_link=db.Column(db.String(100), nullable = True)
    data_link=db.Column(db.String(100), nullable = True)
    slug = db.Column(db.String(20))
    bg_img = db.Column(db.String(50), nullable = False, server_default = '') #set a default bg img
    comments = db.relationship('Comment', lazy=True, backref="Posts")
    imgs = db.relationship('EventImgs', lazy=True, backref="pics", cascade="all, delete-orphan") 

    def __init__(self, *args, **kwargs):
        if not 'slug' in kwargs:
            kwargs['slug'] = slugify(kwargs.get('title'))
            super().__init__(*args, **kwargs)

    def __repr__(self) :
        return f" Event{self.title}, {self.end_date} "

and here is the query I'm trying to use.这是我正在尝试使用的查询。

todays_date = datetime.now
current = Events.query.filter(Events.end_date >= todays_date).all()
past = Events.query.filter(Events.end_date <= todays_date).all()

But I can't find the right way to get this query to work, either I get a blank set, or in the case of this post, I get the following error.但是我找不到让这个查询工作的正确方法,要么我得到一个空白集,要么在这篇文章的情况下,我得到以下错误。

sqlalchemy.exc.StatementError: (builtins.TypeError) SQLite DateTime type only accepts Python datetime and date objects as input.
[SQL: SELECT events.id AS events_id, events.title AS events_title, events.start_date AS events_start_date, events.end_date AS events_end_date, events.body AS events_body, events.form_link AS events_form_link, events.data_link AS events_data_link, events.slug AS events_slug, events.bg_img AS events_bg_img
FROM events
WHERE events.end_date >= ?]
[parameters: [immutabledict({})]]

What's the best way to get the queries to work properly?使查询正常工作的最佳方法是什么?

Blank set returned means it could not fetch any records matching the query, do you get the records from db directly when using same query?返回的空白集意味着它无法获取与查询匹配的任何记录,您在使用相同查询时是否直接从 db 获取记录?

For the second issue please update the code to use datetime.now() instead of datetime.now .对于第二个问题,请更新代码以使用datetime.now()而不是datetime.now

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

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