简体   繁体   English

如何组织SQLAlchemy关系以进行类似JSON的字典访问?

[英]How can I organize SQLAlchemy relationships for access like a JSON-like dict?

I have an application where each user can have many different clothing sizes associated with their account. 我有一个应用程序,其中每个用户可以拥有与其帐户相关联的许多不同的服装尺寸。 I have modeled these associations with association tables, and linked them through relationship() s in my models. 我已经使用关联表对这些关联进行了建模,并通过模型中的relationship()链接了它们。 Before I began trying to shove the relationships into a dictionary, they were linked at the top level, like so: 在我开始尝试将这些关系推入字典之前,它们是在顶级链接的,如下所示:

class User(db.Model):

    id = db.Column(db.Integer, primary_key=True)

    # user many-to-many size associations (using link tables)
    sz_shirt_dress_sleeve = db.relationship(
        'SizeKeyShirtDressSleeve',
        secondary=LinkUserSizeShirtDressSleeve,
        backref=db.backref('users', lazy='dynamic'))
    sz_shirt_dress_neck = db.relationship(
        'SizeKeyShirtDressNeck',
        secondary=LinkUserSizeShirtDressNeck,
        backref=db.backref('users', lazy='dynamic'))
    sz_shirt_casual = db.relationship(
        'SizeKeyShirtCasual',
        secondary=LinkUserSizeShirtCasual,
        backref=db.backref('users', lazy='dynamic'))

And I could access them like so: 我可以这样访问它们:

>>> from app.models import User
>>> u1 = User.query.first()
>>> u1.sz_shirt_dress_sleeve
[Dress shirt sleeve size: 3000]

Because I will eventually have ~20 of these relationships, and because I want to access them more programmatically elsewhere, I would like to store them in a JSON looking dict like this: 因为我最终将拥有约20个这些关系,并且因为我想以编程方式在其他地方访问它们,所以我想将它们存储在JSON格式的dict中,如下所示:

class User(db.Model):

    id = db.Column(db.Integer, primary_key=True)

    sizes = {
        'shirt-sleeve': {
            'key': 'shirt-sleeve',
            'values': db.relationship(
                'SizeKeyShirtDressSleeve',
                secondary=LinkUserSizeShirtDressSleeve,
                backref=db.backref('users', lazy='dynamic'))
        }
    }

By doing that, I would be able to access the list of sizes like this: 这样,我就可以访问如下尺寸列表:

>>> <some_user>.sizes['shirt-sleeve']['values']
[3000, 3050, 3100]

The above attempt at fitting these associations inside a dict doesn't work, as I've found, because "[SQLAlchemy's use of metaclasses] doesn't pick up these objects inside something else like a dictionary." 正如我发现的那样,上述尝试将这些关联适合于dict中是行不通的,因为“ [[SQLAlchemy对元类的使用]不会在字典等其他对象中拾取这些对象。” Well crap. 好废话

In a roundabout way to I tried to appease the metaclass top level sensing with this: 通过一种round回的方式,我试图以此来安抚元类顶级感知:

class User(db.Model):

    id = db.Column(db.Integer, primary_key=True)

    sz_shirt_dress_neck = db.relationship(
        'SizeKeyShirtDressNeck',
        secondary=LinkUserSizeShirtDressNeck,
        backref=db.backref('users', lazy='dynamic'))

    sizes = {
        'shirt-neck': {
            'key': 'shirt-neck',
            'values': lambda self: self.sz_shirt_dress_neck
        }
    }

That didn't work (though it didn't error either): 那没有用(尽管也没有错误):

>>> from app.models import User
>>> u1 = User.query.first()
>>> u1.sizes['shirt-neck']['values']
<function User.<lambda> at 0x102aedb70>

How can I store these relationships in a JSON like dictionary? 如何将这些关系存储在像字典这样的JSON中? (and a small side question: where can I learn design principles to teach me if I should do it this way? I'm self taught and these larger design concepts aren't really covered by documentation/tutorials) (还有一个小问题:如果我应该这样做,我在哪里可以学到设计原理来教我?我是自学成才,而文档/教程并未真正涵盖这些较大的设计概念)

Define a method on your model and modify User object then return it: 在模型上定义一个方法并修改User对象,然后返回它:

class User(db.Model):
    # your codes...
    def as_dict(self):
        self.sizes = {
            'shirt-neck': {
                'key': 'shirt-neck',
                'values': self.sz_shirt_dress_neck
            },
            # another one
        }
        return self


>>> u1 = User.query.first()
>>> if u1:
...     user = u1.as_dict()
...     user.sizes

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

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