我正在建立一个系统,用户可以向另一个用户发出请求,而其他用户可以接受该请求。我希望该请求包含来自users表和我的请求表的数据。
我的用户表和用户请求设置了多对多的数据库关系
SentRequests = db.Table('sentrequests',
db.Column('user_origin', db.Integer, db.ForeignKey('requests.user_origin')),
db.Column('users', db.Integer, db.ForeignKey('users.id')))
RecievedRequests = db.Table('recievedrequests',
db.Column('user_destination', db.Integer, db.ForeignKey('requests.user_destination')),
db.Column('users', db.Integer, db.ForeignKey('users.id')))
class Users(db.Model):
__tablename__ = 'users'
email = db.Column(db.String(120), unique=True, index=True)
id = db.Column(db.Integer, primary_key=True)
password = db.Column(db.Text)
firstname = db.Column(db.String(120))
lastname = db.Column(db.String(120))
type = db.Column(db.String(10))
active = db.Column(db.Boolean)
address = db.Column(db.Text)
latitude = db.Column(db.Float)
longitude = db.Column(db.Float)
uid = db.Column(db.Text(64), unique=True)
requests = db.relationship('Requests', secondary='recievedrequests', lazy='dynamic', backref=db.backref('getusers', lazy='dynamic'))
# group_id = db.Column(db.Integer)
def __init__(self, email, password, firstname, lastname, utype, uid, active=True):
self.password = password
self.firstname = firstname
self.lastname = lastname
self.email = email
self.type = utype
self.active = active
self.uid = uid
@property
def is_active(self):
return self.active
@property
def is_authenticated(self):
return True
@property
def is_anonymous(self):
return True
def get_id(self):
return unicode(self.id)
def __repr__(self):
return '<Users %r>' % self.email
class Requests(db.Model):
__tablename__ = 'requests'
id = db.Column(db.Integer, primary_key=True)
user_origin = db.Column(db.Integer)
user_destination = db.Column(db.Integer)
message = db.Column(db.Unicode)
accepted = db.Column(db.Boolean)
users = db.relationship('Users', secondary='sentrequests', lazy='dynamic', backref=db.backref('getrequests', lazy='dynamic'))
def __init__(self, user_origin, user_destination, accepted=False):
self.user_origin = user_origin
self.user_destination = user_destination
self.accepted = accepted
现在我像这样查询请求表。从我在一小时左右的时间里看到如何做我想做的事情,看起来这是错误的做法。我尝试了.join()
,但这只是让查询返回None
结果
requests = Requests.query.filter_by(user_destination=current_user.id).all()
return render_template('dashboard.html', requests=requests)
我的目标是在模板上我可以从用户表中获取firstname和lastname以及来自请求的消息。
{% for req in requests %}
<p>{{ req.users.firstname }} {{ req.users.lastname }}</p>
<p>{{ req.message }}</p>
{% endfor %}