简体   繁体   English

在 Flask SQLALchemy 模型中处理业务逻辑的正确方法是什么?

[英]What's the proper way of handling business logic in Flask SQLALchemy models?

I'm wondering what's the proper way of retrieving data from the model. Let's take the classes below for the example:我想知道从 model 中检索数据的正确方法是什么。让我们以下面的类为例:

class A(db.Model):
   def get_attributes():
       return self.product_category.attributes
class Attribute(db.Mdel):
    attribute_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    label = db.Column(db.String(255), nullable=False)

Let's say that calling get_attributes() returns three objects of the Attribute class.假设调用get_attributes()返回属性 class 的三个对象。

In my route , I only want to receive the list of attribute labels.在我的路线中,我只想接收属性标签列表。 What I'm currently doing is looping through the objects and retrieve the label property like this:我目前正在做的是循环遍历对象并检索 label 属性,如下所示:

labels = [i.label for i in obj.get_attributes()]

Which I don't think is a proper way of doing it.我认为这不是正确的做法。 Is there any better way to achieve this?有没有更好的方法来实现这一目标?

You should use relationship between A and Attribute.您应该使用 A 和属性之间的 关系

For example例如

class A(db.Model):
    # ...
    # table primary key, columns etc.
    # ...
    attributes = db.relationship(
        "Attribute",
        backref="as",
        lazy=True
    )

class Attribute(db.Model):
    # ...
    # table primary key, columns etc.
    # ...
    a_id = db.Column(db.Integer, db.ForeignKey('a.id'))

After that, you can access certain "a" attributes with a.attributes.之后,您可以使用 a.attributes 访问某些“a”属性。 To add an attribute to "a" just: a.attributes.append(a)只需将属性添加到“a”:a.attributes.append(a)

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

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