2. Interview Questions- ORM Mapped Class Configuration
Source: https://docs.sqlalchemy.org/en/20/orm/mapper_config.html
1. What are the two primary styles of ORM mapper configuration in SQLAlchemy?
Answer:
Declarative mapping: Defines mapping within the class body using
DeclarativeBase.Imperative (classical) mapping: Uses
mapper()to link a class to aTableobject explicitly.
2. What is the recommended approach for mapping in modern SQLAlchemy?
Answer:
Declarative mapping using DeclarativeBase is recommended for most use cases due to its simplicity and clarity.
3. How do you declare a mapped class using declarative mapping?
Answer:
class MyClass(Base):
__tablename__ = "my_table"
id: Mapped[int] = mapped_column(primary_key=True)4. How is table metadata associated with a declarative model?
Answer:
Declarative models use __tablename__ and mapped_column() definitions to automatically create a Table object via Base.metadata.
5. What is imperative mapping?
Answer:
It’s a manual approach where you create a Table object and then map it to a class using the mapper() function.
6. What function is used for classical (imperative) mapping?
Answer:
mapper() from sqlalchemy.orm.
7. How do you define a mapped class using imperative mapping?
Answer:
8. What is registry() in SQLAlchemy ORM?
registry() in SQLAlchemy ORM?Answer: A factory for generating mappers and managing metadata in both declarative and classical configurations.
9. How do you declare mixins in SQLAlchemy ORM?
Answer: By creating a class that is not mapped itself but is inherited by mapped classes to reuse fields or methods.
10. What is the role of __mapper_args__?
__mapper_args__?Answer:
It's a dictionary used to pass additional options to the mapper, such as polymorphic_identity, order_by, or eager_defaults.
11. What does __table__ signify in a mapped class?
__table__ signify in a mapped class?Answer:
It directly assigns a Table object to a class, overriding the automatic table construction from __tablename__.
12. Can a single class be mapped to multiple tables?
Answer: No, a class can only map to one table directly, but joined-table inheritance can involve multiple tables.
13. How do you specify a custom primary key in declarative mapping?
Answer:
By using mapped_column(primary_key=True) and not relying on defaults.
14. How do mixins interact with __tablename__?
__tablename__?Answer:
Mixins should not define __tablename__. The final concrete class must define it.
15. Can you define relationships in a mixin class?
Answer: Yes, you can define relationships in mixins using standard ORM syntax.
16. What is a declarative registry?
Answer:
An object that holds class mappings and metadata, typically instantiated via DeclarativeBase or registry().
17. What does __allow_unmapped__ = True do?
__allow_unmapped__ = True do?Answer: It allows the class to include attributes that SQLAlchemy will ignore (not map) without raising an error.
18. How can you override default behavior in class mappings?
Answer:
Use __mapper_args__ or custom column definitions using mapped_column() or manually define __table__.
19. What’s the difference between mapped_column() and Column()?
mapped_column() and Column()?Answer:
mapped_column()is used in declarative classes and includes type hinting.Column()is used in classical table definitions.
20. How do you reflect a table for use in imperative mapping?
Answer:
21. What does the eager_defaults mapper argument do?
eager_defaults mapper argument do?Answer: It enables automatic fetching of default values set by the database (e.g., server-side defaults) after an INSERT.
22. What is polymorphic_on used for in __mapper_args__?
polymorphic_on used for in __mapper_args__?Answer: It defines the column used to distinguish between subclasses in a polymorphic inheritance mapping.
23. What does polymorphic_identity signify in a mapped class?
polymorphic_identity signify in a mapped class?Answer:
It defines the identifier used in the polymorphic_on column to associate a subclass with a specific value.
24. How do you specify ordering for a mapped class using __mapper_args__?
__mapper_args__?Answer:
By setting order_by to a column or list of columns.
25. Can you use SQLAlchemy ORM without declaring a Base class?
Base class?Answer:
Yes, using classical mapping with mapper() and a registry() is possible without a base class.
26. What happens if two classes define the same __tablename__?
__tablename__?Answer: SQLAlchemy will raise an error during metadata creation due to table name conflict.
27. How do you create an abstract base class that isn’t mapped itself?
Answer:
Use __abstract__ = True in the class body.
28. What does __abstract__ = True do?
__abstract__ = True do?Answer: It tells SQLAlchemy not to map the class even though it inherits from a declarative base.
29. What is the purpose of a mixin class in SQLAlchemy?
Answer: To reuse common columns, constraints, relationships, or methods across multiple models.
30. Can mixins contain foreign key relationships?
Answer: Yes, mixins can define relationships and foreign key columns, which are inherited by mapped subclasses.
31. What is the difference between __tablename__ and __table__ in a model class?
__tablename__ and __table__ in a model class?Answer:
__tablename__lets SQLAlchemy auto-create the table.__table__directly assigns an existingTableobject.
32. How can you exclude a column from being mapped in a declarative class?
Answer:
Either don’t annotate with Mapped[...] or set __allow_unmapped__ = True to prevent errors for unmapped attributes.
33. What is the use of declarative_mixin decorator?
declarative_mixin decorator?Answer: It marks a class as a mixin, clarifying its purpose and suppressing mapping unless inherited.
34. Can mixins override columns from the parent class?
Answer: Yes, but care must be taken to avoid conflicts during mapping.
35. How do you define joined-table inheritance in declarative mapping?
Answer:
36. Can a model define __mapper_args__ without defining __tablename__?
__mapper_args__ without defining __tablename__?Answer:
No, unless __table__ is manually assigned. Otherwise, the table mapping will be incomplete.
37. What is the impact of omitting Mapped[...] in a declarative field?
Mapped[...] in a declarative field?Answer: SQLAlchemy may not include it in the mapping, and a warning or error may be raised in strict configurations.
38. How do you ensure compatibility with Python static type checkers in SQLAlchemy?
Answer:
Use Mapped[T] for fields and mapped_column() for column definitions.
39. What happens when registry().map_imperatively() is called more than once for the same class?
registry().map_imperatively() is called more than once for the same class?Answer: An error is raised since a class can only be mapped once in a given registry context.
40. How does SQLAlchemy handle attribute name clashes between mixins and subclasses?
Answer: The subclass overrides the mixin’s attribute. The last defined attribute takes precedence in the class hierarchy.
41. What is the function of __init__() in declarative models?
__init__() in declarative models?Answer:
SQLAlchemy auto-generates an __init__() method that accepts keyword arguments for mapped fields. You can override it, but it’s typically not necessary unless custom logic is required.
42. How does SQLAlchemy determine which attributes to map when using declarative mapping?
Answer:
It maps attributes annotated with Mapped[...] and defined using mapped_column(). Unannotated fields are ignored unless explicitly handled.
43. How can you control if a class should be mapped at runtime?
Answer:
Use __abstract__ = True to skip mapping for base/mixin classes, or delay mapping with registry().map_imperatively() manually.
44. What happens if you declare a field with mapped_column() but forget Mapped[...]?
mapped_column() but forget Mapped[...]?Answer: The field may not be registered correctly in the mapping. Static typing tools may also miss it, and SQLAlchemy may ignore it depending on configuration.
45. Why is registry.metadata preferred in imperative mapping over standalone MetaData?
registry.metadata preferred in imperative mapping over standalone MetaData?Answer:
registry.metadata ensures a consistent metadata registry for all ORM-mapped classes, enabling unified DDL generation and schema management.
46. How does SQLAlchemy know a class is "mapped"?
Answer:
A class is considered mapped if it’s registered in the declarative base or explicitly mapped via map_imperatively().
47. What error will you get if you access .metadata on a model class that isn't properly mapped?
.metadata on a model class that isn't properly mapped?Answer:
You may get an AttributeError or mapping exception because the class lacks an associated Table or metadata.
48. Can you modify __mapper_args__ dynamically at runtime?
__mapper_args__ dynamically at runtime?Answer: Yes, though it’s uncommon. You can override it in the class definition based on environment or configuration.
49. How does SQLAlchemy differentiate between regular attributes and mapped columns in declarative mapping?
Answer:
By type annotations with Mapped[...] and use of mapped_column() function. Attributes without these are treated as regular Python attributes.
50. What is the impact of assigning __table_args__ in a declarative class?
__table_args__ in a declarative class?Answer:
__table_args__ lets you define additional table-level arguments like indexes, constraints, and engine-specific options.
Last updated