我正在将Flask SQLAlchemy用于我的项目,并且我意识到我的客户页面非常慢,因为我正在尝试为每个客户获取目标。我的结构看起来像这样。
class Users(db.Model):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
first_name = db.Column(db.String(200), nullable=False)
last_name = db.Column(db.String(30), nullable=False)
created_date = db.Column(db.DateTime,nullable=False,default=datetime.datetime.now())
email = db.Column(db.Unicode(50), nullable=False)
account = db.Column(db.Unicode(10), nullable=False)
number = db.Column(db.String(30), nullable=False)
user_type = db.Column(db.String(10), nullable=False, default='ADMIN')
created_by = db.Column(db.Unicode(10), nullable=False, default='SYSTEM')
destinations = db.relationship('Destinations', backref="customer",lazy="dynamic")
class Destinations(db.Model):
__tablename__ = 'destinations'
import datetime
id = db.Column(db.Integer, primary_key = True)
did = db.Column(db.Text, nullable=False)
gateway = db.Column(db.Text, nullable=False)
channel = db.Column(db.Text, nullable=False)
own = db.Column(db.Text, nullable=False)
number = db.Column(db.Unicode(50), nullable=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
created_by = db.Column(db.Integer,nullable=False)
created_date = db.Column(db.DateTime, default=datetime.datetime.now())
expire_date = db.Column(db.DateTime, nullable=False)
record = db.Column(db.Integer, nullable=False)
auth_did = db.Column(db.Integer, nullable=False)
auth_gw = db.Column(db.Integer, nullable=False)
在我的所有客户页面中,我会快速列出请求的所有客户,但是当我尝试为每个客户加载所有目的地时,请求会花费大量时间来加载。
{% for customer in customers %}
<tr>
<td>{{customer.first_name}}</td>
<td>{{customer.number}}</td>
<td>
{% for destination in customer.destinations %}
{{destination.number}}<br />
{% endfor %}
</td>
<td>
{% for destination in customer.destinations %}
{{destination.did}}<br />
{% endfor %}
</td>
<td>
{% for destination in customer.destinations %}
{{destination.own}}<br />
{% endfor %}
</td>
<td>
{% for destination in customer.destinations %}
{{destination.created_date|humandatetime|safe}}<br />
{% endfor %}
</td>
<td>
{% for destination in customer.destinations %}
{% if destination.expire_date %}{{destination.expire_date|humandatetime|safe}}{% endif %}<br />
{% endfor %}
</td>
<td>
{% for destination in customer.destinations %}
{{destination.gateway or ''}}<br />
{% endfor %}
</td>
<td>
{% for destination in customer.destinations %}
{{destination.channel or ''}}<br />
{% endfor %}
</td>
<td>
{% for destination in customer.destinations %}
<a href="/customers/destinations/delete/{{destination.did}}/{{destination.id}}">del</a><br />
{% endfor %}
</td>
<td><input type="hidden" value="{{customer.first_name}} {{customer.last_name}}"></td>
<td><a id="{{customer.id}}" class="user-delete-icon">delete</a></td>
</tr>
{% endfor %}
此功能也是让我所有客户都能获得此功能的
customers = db.session.query(Users).filter_by(user_type='CUST').all()
我认为问题是关系类型懒惰但我无法修复它