I have a Flask app which uses Flask-admin for a dashboard and raw model object manipulation. The app has a User
class for users who sign into the site, and a Contact
class for contacts entered by each user.
I want each row in the Contact tab in Flask-admin to display the email of the user who entered it. I have set up the code like this:
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
contacts = db.relationship('Contact', backref='user')
# [...]
def __repr__(self):
return f'{self.email}'
class Contact(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
# [...]
The User column does not appear with this setup. I am not excluding it using column_exclude_list
. I tried using column_list
to explicitly show the 'user' column, and that DID show a column—but it was empty. (I will ultimately be using this, but I've turned it off for now to simplify things.)
Beyond implementing __repr__()
and including a relationship with a backref linking the two model objects, what do I need to do to make this column appear? How can I debug why it's not showing up?
I did notice at one point that I had a second relationship declared with a backref also called 'user'
on the Export class. Export.user was working! When I first noticed this, I disabled the second relationship, but that didn't fix the Contact.user relationship.
In the course of writing up this question, I worked out what was wrong. I had a function which I was using to fetch the Contacts entered by a given User. That function?
class User(UserMixin, db.Model):
def contacts(self):
return db.session.query(Contact).filter(Contact.user_id == current_user.id)
So the contacts
function was conflicting with the contacts
relationship static variable. Once I renamed the function, the column appeared as expected.