Creating one-to-one relationship Flask-SQLAlchemy
Asked Answered
U

1

2

I am trying to create a one-to-one relationship between a Department & Ticket table. This way when looking inside of Flask-Admin a user would be able to see the Department name instead of the ID.

I have tried to setup the relationship 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 are:

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:

Department Admin View

Single Ticket Edit: Department Dropdown

How would I go about showing the Department name instead of the memory location?

Unquestionable answered 10/4, 2017 at 20:39 Comment(2)
For the one-to-one see https://mcmap.net/q/277542/-how-to-create-one-to-one-relationships-with-declarativeKurrajong
department = db.relationship('Departments', backref=backref("tickets", uselist=False)) the uselist=False might fix your view problems as wellKurrajong
M
4

Define function __repr__ of Department.

class Department(db.Model)
    # ... column definition

    def __repr__(self):
        return self.name

The __repr__ will show the name of department instead the inner representation of object.

PS: uselist=0 is the key to define a one to one relationship in SQLAlchemy.

Montymonument answered 11/4, 2017 at 4:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.