我有一个应用程序,每个用户可以有多种不同的服装尺寸与他们的帐户相关联。我已经将这些关联建模为关联表,并通过我的模型中的relationship()
链接它们。在我开始尝试将关系推入字典之前,它们是在顶层链接的,如下所示:
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'))
我可以这样访问它们:
>>> from app.models import User
>>> u1 = User.query.first()
>>> u1.sz_shirt_dress_sleeve
[Dress shirt sleeve size: 3000]
因为我最终会有大约20个这样的关系,并且因为我想在其他地方以编程方式访问它们,所以我想将它们存储在像这样的JSON看法中:
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'))
}
}
通过这样做,我将能够访问这样的大小列表:
>>> <some_user>.sizes['shirt-sleeve']['values']
[3000, 3050, 3100]
正如我所发现的那样,上述在dict中拟合这些关联的尝试是行不通的,因为"[SQLAlchemy's use of metaclasses] doesn't pick up these objects inside something else like a dictionary."好吧。
我以迂回的方式尝试用这个来安抚元类顶级传感:
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
}
}
这不起作用(虽然它也没有错误):
>>> from app.models import User
>>> u1 = User.query.first()
>>> u1.sizes['shirt-neck']['values']
<function User.<lambda> at 0x102aedb70>
如何将这些关系存储在类似字典的JSON中? (还有一个小问题:如果我应该这样做,我可以在哪里学习设计原则来教我?我是自学的,这些较大的设计概念并没有真正涵盖在文档/教程中)
答案 0 :(得分:0)
在模型上定义方法并修改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