Creating one-to-one Flask-SQLAlchemy relationships

I am trying to create a one-to-one relationship between Department and Ticket tables. Thus, if you look inside Flask-Admin , the user will be able to see the name Department instead of the identifier.

I tried to establish the relation as follows:

 # Ticket Table class Tickets(db.Model): __tablename__ = 'tickets' ticketID = db.Column(db.Integer, nullable=False, primary_key=True, autoincrement=True, unique=True) cust_name = db.Column(db.String(50), nullable=False) cust_email = db.Column(db.String(50), nullable=False) cust_phone = db.Column(db.Integer, nullable=False) tix_dept = db.Column(db.Integer, db.ForeignKey('department.deptID')) tix_severity = db.Column(db.Integer, nullable=False) tix_msg = db.Column(db.String(500), nullable=False) tix_status = db.Column(db.String(10), nullable=False) tix_recv_date = db.Column(db.String(20), nullable=False) tix_recv_time = db.Column(db.Integer, nullable=False) # define relationship department = db.relationship('Departments') # Department Table class Departments(db.Model): __tablename__ = 'department' deptID = db.Column(db.Integer, primary_key=True, autoincrement=True, unique=True) dept_name = db.Column(db.String(40), nullable=False) dept_empl = db.Column(db.String(40), nullable=False) dept_empl_phone = db.Column(db.Integer, nullable=False) 

Then my Flask-Admin views:

 admin.add_view(TicketAdminView(Tickets, db.session, menu_icon_type='glyph', menu_icon_value='glyphicon-home')) admin.add_view(DepartmentAdminView(Departments, db.session)) 

Admin panel for tickets:

Admin admin view

Editing a single ticket: Division Division

How do I show the name Department instead of a memory location?

+2
source share
1 answer

Define the __repr__ Department function.

 class Department(db.Model) # ... column definition def __repr__(self): return self.name 

__repr__ will display the department name instead of the internal representation of the object.

PS: uselist=0 is the key to determine the one-to-one relationship in SQLAlchemy.

+4
source

Source: https://habr.com/ru/post/1266345/


All Articles