0

Let's say I have a model like:

from sqlalchemy import Column, DateTime, ForeignKey, Text

class Foo(declarative_base):
    __tablename__ = "foos"
    my_dt = Column(DateTime...)
    my_other_value = Column(Integer...)

I'm trying to make a UniqueConstraint using SqlAlchemy notation that would only allow one my_other_value per day, which means, I'd like to extract the Date part of my_dt and Uniquely constraint it with my_other_value

I know (erm... I'm fairly sure I know, rather) how to do it in PostgreSQL:

CREATE UNIQUE INDEX unique_num_and_date 
ON foos(my_other_value, date_trunc('day',my_dt));

but just out of curisity/consitency, I'd like to reflect that using SqlAlchemy.

Savir
  • 17,568
  • 15
  • 82
  • 136

1 Answers1

0

Try something like this:

class MyModel(Base):
    __tablename__ = 'my_model'
    __table_args__ = (UniqueConstraint('name', 'deleted_at'),)
    name = Column(String(length=64), nullable=False)
    deleted_at = Column(DateTime(), nullable=True)
phrfpeixoto
  • 191
  • 1
  • 2
  • 11
  • Thanks for the answer! However, what I'm trying to do is extracting the `Date` part of the `DateTime` column and use that in the constraint itself. It would be something like: `__table_args__ = ( UniqueConstraint('name', function_that_i_am_looking_for_that_extracts_the_date_from_column('deleted_at')),)` Sorry if the question wasn't clear. – Savir Sep 19 '19 at 19:35