Storing a PostgreSQL ARRAY of ENUM values

后端 未结 1 1542
误落风尘
误落风尘 2021-01-14 04:22

I have a table that can have a status:

statuses = [\'unmoderated\', \'nominee\', \'finalist\', \'winner\']
status = db.Enum(
    *statuses, name=\'enum_nomin         


        
相关标签:
1条回答
  • 2021-01-14 05:09

    I looked at Issue 3467 posted by Wichert Akkerman, and this work-around was posted. Credit to Mike Bayer. Declare the following class in your code (with the necessary imports, of course):

    from sqlalchemy.dialects.postgresql import ARRAY
    from sqlalchemy import cast
    
    class ArrayOfEnum(ARRAY):
        def bind_expression(self, bindvalue):
            return cast(bindvalue, self)
    
        def result_processor(self, dialect, coltype):
            super_rp = super(ArrayOfEnum, self).result_processor(dialect, coltype)
    
            def handle_raw_string(value):
                if value==None:
                    return []
                inner = re.match(r"^{(.*)}$", value).group(1)
                return inner.split(",")
    
            def process(value):
                return super_rp(handle_raw_string(value))
            return process
    

    ArrayOfEnum is now a special column type that gets used in the model definition.

    So instead of

    class Judge(db.Model):
        statuses = db.Column(ARRAY(status))
    

    Now you can do:

    class Judge(db.Model):
        statuses = db.Column(ArrayOfEnum(status))
    

    Now in your code you can assign values to statuses with a list and it will do the proper casting upon saving:

    my_judge_object.status = ['unmoderated', 'nominee']
    
    0 讨论(0)
提交回复
热议问题