Skip to content

Conversation

@sachin-gracious
Copy link

Fixes validation errors when creating/editing records with required foreign key relationships by using SQLAlchemy introspection to automatically populate FK columns.

Problem:

  • _arrange_data loaded relationship objects but didn't populate FK columns
  • Pydantic validation failed with 'Field required' error
  • Only affected MANYTOONE (HasOne) relationships with required FKs

Solution:

  • Use SQLAlchemy's inspect() and synchronize_pairs to discover FK columns
  • Works with ANY FK naming (user_id, owner_id, created_by, etc.)
  • Works with ANY PK naming (id, uuid, etc.)
  • Handles composite keys, None relationships, self-referential FKs
  • Does NOT affect ONETOMANY or MANYTOMANY relationships

Changes:

  • Modified: starlette_admin/contrib/sqla/view.py (_arrange_data method)
  • Added: tests/sqla/test_sqlmodel_custom_fk.py (custom FK naming tests)
  • Added: tests/sqla/test_sqlmodel_manytomany.py (association table tests)
  • All 94 tests pass (87 existing + 7 new)

Fixes: #485, #687

Fixes validation errors when creating/editing records with required foreign key relationships by using SQLAlchemy introspection to automatically populate FK columns.

Problem:
- _arrange_data loaded relationship objects but didn't populate FK columns
- Pydantic validation failed with 'Field required' error
- Only affected MANYTOONE (HasOne) relationships with required FKs

Solution:
- Use SQLAlchemy's inspect() and synchronize_pairs to discover FK columns
- Works with ANY FK naming (user_id, owner_id, created_by, etc.)
- Works with ANY PK naming (id, uuid, etc.)
- Handles composite keys, None relationships, self-referential FKs
- Does NOT affect ONETOMANY or MANYTOMANY relationships

Changes:
- Modified: starlette_admin/contrib/sqla/view.py (_arrange_data method)
- Added: tests/sqla/test_sqlmodel_custom_fk.py (custom FK naming tests)
- Added: tests/sqla/test_sqlmodel_manytomany.py (association table tests)
- All 94 tests pass (87 existing + 7 new)

Fixes: jowilf#485, jowilf#687
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: Required foreign key is empty

1 participant