Skip to content

Better field name for relationships (many side) #377

Open
@krr0land

Description

@krr0land

Things to check first

  • I have searched the existing issues and didn't find my feature already requested there

Feature description

When dealing with one-to-many relationships the names of the fields on the 'one' side is currently using the Table's name. When you have multiple foreign keys with that table, an underscore is appended.

Example:

class Points(SQLModel, table=True):
    __tablename__ = 'Points'
    __table_args__ = (PrimaryKeyConstraint('id', name='PK_Points'))
    id: Optional[int] = Field(default=None, sa_column=Column('id', Integer, Identity(start=1, increment=1), primary_key=True))

    Lines: List['Lines'] = Relationship(back_populates='point_a')
    Lines_: List['Lines'] = Relationship(back_populates='point_b')


class Lines(SQLModel, table=True):
    __tablename__ = 'Lines'
    __table_args__ = (
        ForeignKeyConstraint(['point_a_id'], ['Points.id'], name='FK__Point_A__Lines__Points'),
        ForeignKeyConstraint(['point_b_id'], ['Points.id'], name='FK__Point_B__Lines__Points'),
        PrimaryKeyConstraint('id', name='PK_Lines')
    )

    id: Optional[int] = Field(default=None, sa_column=Column('id', Integer, Identity(start=1, increment=1), primary_key=True))    
    point_a_id: int = Field(sa_column=Column('point_a_id', Integer))
    point_b_id: int = Field(sa_column=Column('point_b_id', Integer))

    point_a: Optional['Points'] = Relationship(back_populates='Lines')
    point_b: Optional['Points'] = Relationship(back_populates='Lines_')

In the 'Lines' class the relationships are called point_a and point_b however on the Point's class, they are called Lines and Lines_, which makes it hard to understand. (This is example is not the best in terms of naming, but hopefully the issue is visible.)

Solution Proposal:
Include the either the FK or the back populates in the field name:

Lines -> Lines_point_a
Lines_ -> Lines_point_b

Or something similar. This should only happen if there are multiple foreign keys are present for the same table.

Use case

Improves readability of the code, and makes more sense.

Might have to make it optional, as it might break existing code.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions