简体   繁体   中英

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. All the current posts would be on one list, and the expired posts would be on another list.

Here is the 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?

For the second issue please update the code to use datetime.now() instead of datetime.now .

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