Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Current Date in SQLAlchemy ORM relationship

I'm trying to configure a relationship between two objects based on the current date. Say I have a Person object and a relationship to a bunch of Event objects. If the Event object holds a DateTime (start) on it, I want to make a relationship to all of today's events.

So far I have:

class Person:
    id = Column(Integer, primary_key=True)
    todays_events = relationship('Event', primaryjoin='and_(Person.id == Event.person_id, cast(Event.start, Date) == "2016-04-23"')

This works but I can't find what I need to replace the date string with "2016-04-23" to get the equivalent of CURDATE().

Does anyone know what I'm looking for?

Thanks.

like image 298
freebie Avatar asked Apr 23 '16 11:04

freebie


People also ask

How would you describe the relationship between tables using ORM?

Usually, the Table uses the MetaData object associated with the declarative base class, so that the ForeignKey directives can locate the remote tables with which to link. The relationship. back_populates parameter for each relationship() establishes a bidirectional relationship.

What is Server_default in SQLAlchemy?

A client-side SQL expression, a server_default value, and server-side implicit defaults and triggers all have the server generate the default, which then must be fetched by the client if you want to be able to access it in the same SQLAlchemy session.

How does SQLAlchemy relationship work?

The simple way to declare relationship is user = relationship(Users) in OpenID class. You may also use users = relationship('OpenID') in Users class. backref parameter allows you to declare both relationships with single declaration: it means to automatically install backward relationship in related class.

What is Back_populates in SQLAlchemy?

The back_populates argument tells SqlAlchemy which column to link with when it joins the two tables. It allows you to access the linked records as a list with something like Parent.


1 Answers

Found the answer right after posting... of course.

func.current_date()

so:

class Person:
     id = Column(Integer, primary_key=True)
     todays_events = relationship('Event', primaryjoin='and_(Person.id == Event.person_id, cast(Event.start, Date) == func.current_date()')
like image 140
freebie Avatar answered Sep 23 '22 00:09

freebie