简体   繁体   English

在Flask-SqlAlchemy和MySQL中处理数组

[英]Dealing with Arrays in Flask-SqlAlchemy and MySQL

I have a datamodel where I store a list of values separated by comma (1,2,3,4,5...). 我有一个数据模型,在其中存储用逗号(1,2,3,4,5 ...)分隔的值列表。

In my code, in order to work with arrays instead of string , I have defined the model like this one: 在我的代码中,为了使用arrays而不是string ,我定义了如下模型:

class MyModel(db.Model):
    pk = db.Column(db.Integer, primary_key=True)
    __fake_array = db.Column(db.String(500), name="fake_array")

    @property
    def fake_array(self):
        if not self.__fake_array:
            return

        return self.__fake_array.split(',')

    @fake_array.setter
    def fake_array(self, value):
        if value:
           self.__fake_array = ",".join(value)
        else:
           self.__fake_array = None

This works perfect and from the point of view of my source code "fake_array" is an array, It's only transformed into string when it's stored in database. 这很完美,从我的源代码的角度来看, “ fake_array”是一个数组,仅当存储在数据库中时才转换为string

The problem appears when I try to filter by that field. 当我尝试按该字段过滤时,会出现问题。 Expressions like this doesn't work: 这样的表达式不起作用:

MyModel.query.filter_by(fake_array="1").all()

It seems that I cant filter using the SqlAlchemy query model . 看来我无法使用SqlAlchemy查询模型进行过滤。

What can I do here? 我在这里可以做什么? Is there any way to filter this kind of fields? 有什么办法可以过滤此类字段? Is there is a better pattern for the "fake_array" problem? 对于“ fake_array”问题,是否有更好的模式?

Thanks! 谢谢!

What you're trying to do should really be replaced with a pair of tables and a relationship between them. 您实际上要用一对表以及它们之间的关系替换您要执行的操作。

The first table (which I'll call A) contains everything BUT the array column, and it should have a primary key of some sort. 第一个表(我将其称为A)包含数组列中的所有内容,并且它应该具有某种主键。 You should have another table (which I'll call B) that contains a primary key, a foreign key column to A (which I'll call a_id, and an integer field. 您应该有另一个表(我将其称为B),该表包含主键,A的外键列(我将其称为a_id)和整数字段。

Using this layout, each row in the A table has its associated array in table B where B's a_id == A.id via a join. 使用此布局,A表中的每一行在表B中都有其关联的数组,其中B的a_id == A.id通过联接。 You can add or remove values from the array by manipulating the rows in table B. You can filter by using a join. 您可以通过处理表B中的行来在数组中添加或删除值。可以使用联接进行过滤。

If the order of the values is needed, then create an order column in table B. 如果需要这些值的顺序,则在表B中创建一个顺序列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM