[Python] sqlalchemy unique across multiple columns

Discussão em 'Python' iniciado por Stack, Junho 26, 2025.

  1. Stack

    Stack Membro Participativo

    Let's say that I have a class that represents locations. Locations "belong" to customers. Locations are identified by a unicode 10 character code. The "location code" should be unique among the locations for a specific customer.

    The two below fields in combination should be unique
    customer_id = Column(Integer,ForeignKey('customers.customer_id')
    location_code = Column(Unicode(10))


    So if i have two customers, customer "123" and customer "456". They both can have a location called "main" but neither could have two locations called main.

    I can handle this in the business logic but I want to make sure there is no way to easily add the requirement in sqlalchemy. The unique=True option seems to only work when applied to a specific field and it would cause the entire table to only have a unique code for all locations.

    Continue reading...

Compartilhe esta Página