Many to One

A many to one relationship associates many children with a single parent. For example, a company can have many employees working in the same division (for example engineering, legal, marketing, …) but a particular employee can only work in one division.

See also

Many to One

OpenAlchemy documentation for many to one relationships.

SQLAlchemy Many to One

SQLAlchemy documentation for many to one relationships.

The following example defines a many to one relationship between Employee and Division:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
openapi: "3.0.0"

info:
  title: Test Schema
  description: API to illustrate Many to One Relationships.
  version: "0.1"

paths:
  /division:
    get:
      summary: Used to retrieve all divisions.
      responses:
        200:
          description: Return all divisions from the database.
          content:
            application/json:
              schema:
                type: array
                items:
                  "$ref": "#/components/schemas/Division"
  /employee:
    get:
      summary: Used to retrieve all employees.
      responses:
        200:
          description: Return all employees from the database.
          content:
            application/json:
              schema:
                type: array
                items:
                  "$ref": "#/components/schemas/Employee"

components:
  schemas:
    Division:
      description: A part of a company.
      type: object
      x-tablename: division
      properties:
        id:
          type: integer
          description: Unique identifier for the division.
          example: 0
          x-primary-key: true
        name:
          type: string
          description: The name of the division.
          example: Engineering
    Employee:
      description: Person that works for a company.
      type: object
      x-tablename: employee
      properties:
        id:
          type: integer
          description: Unique identifier for the employee.
          example: 0
          x-primary-key: true
        name:
          type: string
          description: The name of the employee.
          example: David Andersson
        division:
          "$ref": "#/components/schemas/Division"

The following file uses OpenAlchemy to generate the SQLAlchemy models:

1
2
3
from open_alchemy import init_yaml

init_yaml("example-spec.yml", models_filename="models_auto.py")

The SQLAlchemy models generated by OpenAlchemy are equivalent to the following traditional models file:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()


class Division(Base):
    """Division of a company."""

    __tablename__ = "division"
    id = sa.Column(sa.Integer, primary_key=True)
    name = sa.Column(sa.String)


class Employee(Base):
    """Person that works for a company."""

    __tablename__ = "employee"
    id = sa.Column(sa.Integer, primary_key=True)
    name = sa.Column(sa.String)
    division = sa.orm.relationship("Division")
    division_id = sa.Column(sa.Integer, sa.ForeignKey("division.id"))

OpenAlchemy will generate the following typed models:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
"""Autogenerated SQLAlchemy models based on OpenAlchemy models."""
# pylint: disable=no-member,super-init-not-called,unused-argument

import typing

import sqlalchemy
from sqlalchemy import orm

from open_alchemy import models

Base = models.Base  # type: ignore


class DivisionDict(typing.TypedDict, total=False):
    """TypedDict for properties that are not required."""

    id: typing.Optional[int]
    name: typing.Optional[str]


class TDivision(typing.Protocol):
    """
    SQLAlchemy model protocol.

    A part of a company.

    Attrs:
        id: Unique identifier for the division.
        name: The name of the division.

    """

    # SQLAlchemy properties
    __table__: sqlalchemy.Table
    __tablename__: str
    query: orm.Query

    # Model properties
    id: "sqlalchemy.Column[typing.Optional[int]]"
    name: "sqlalchemy.Column[typing.Optional[str]]"

    def __init__(
        self, id: typing.Optional[int] = None, name: typing.Optional[str] = None
    ) -> None:
        """
        Construct.

        Args:
            id: Unique identifier for the division.
            name: The name of the division.

        """
        ...

    @classmethod
    def from_dict(
        cls, id: typing.Optional[int] = None, name: typing.Optional[str] = None
    ) -> "TDivision":
        """
        Construct from a dictionary (eg. a POST payload).

        Args:
            id: Unique identifier for the division.
            name: The name of the division.

        Returns:
            Model instance based on the dictionary.

        """
        ...

    @classmethod
    def from_str(cls, value: str) -> "TDivision":
        """
        Construct from a JSON string (eg. a POST payload).

        Returns:
            Model instance based on the JSON string.

        """
        ...

    def to_dict(self) -> DivisionDict:
        """
        Convert to a dictionary (eg. to send back for a GET request).

        Returns:
            Dictionary based on the model instance.

        """
        ...

    def to_str(self) -> str:
        """
        Convert to a JSON string (eg. to send back for a GET request).

        Returns:
            JSON string based on the model instance.

        """
        ...


Division: typing.Type[TDivision] = models.Division  # type: ignore


class EmployeeDict(typing.TypedDict, total=False):
    """TypedDict for properties that are not required."""

    id: typing.Optional[int]
    name: typing.Optional[str]
    division: typing.Optional["DivisionDict"]


class TEmployee(typing.Protocol):
    """
    SQLAlchemy model protocol.

    Person that works for a company.

    Attrs:
        id: Unique identifier for the employee.
        name: The name of the employee.
        division: The division of the Employee.

    """

    # SQLAlchemy properties
    __table__: sqlalchemy.Table
    __tablename__: str
    query: orm.Query

    # Model properties
    id: "sqlalchemy.Column[typing.Optional[int]]"
    name: "sqlalchemy.Column[typing.Optional[str]]"
    division: 'sqlalchemy.Column[typing.Optional["TDivision"]]'

    def __init__(
        self,
        id: typing.Optional[int] = None,
        name: typing.Optional[str] = None,
        division: typing.Optional["TDivision"] = None,
    ) -> None:
        """
        Construct.

        Args:
            id: Unique identifier for the employee.
            name: The name of the employee.
            division: The division of the Employee.

        """
        ...

    @classmethod
    def from_dict(
        cls,
        id: typing.Optional[int] = None,
        name: typing.Optional[str] = None,
        division: typing.Optional["DivisionDict"] = None,
    ) -> "TEmployee":
        """
        Construct from a dictionary (eg. a POST payload).

        Args:
            id: Unique identifier for the employee.
            name: The name of the employee.
            division: The division of the Employee.

        Returns:
            Model instance based on the dictionary.

        """
        ...

    @classmethod
    def from_str(cls, value: str) -> "TEmployee":
        """
        Construct from a JSON string (eg. a POST payload).

        Returns:
            Model instance based on the JSON string.

        """
        ...

    def to_dict(self) -> EmployeeDict:
        """
        Convert to a dictionary (eg. to send back for a GET request).

        Returns:
            Dictionary based on the model instance.

        """
        ...

    def to_str(self) -> str:
        """
        Convert to a JSON string (eg. to send back for a GET request).

        Returns:
            JSON string based on the model instance.

        """
        ...


Employee: typing.Type[TEmployee] = models.Employee  # type: ignore

Nullable

The OpenAPI nullable directive can be used to control the nullability of the many to one relationship.

See also

Nullable

OpenAlchemy documentation for the nullability of many to one relationships.

The following example defines a many to one relationship between Employee and Division that is not nullable:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
openapi: "3.0.0"

info:
  title: Test Schema
  description: API to illustrate Many to One Relationships that are not nullable.
  version: "0.1"

paths:
  /division:
    get:
      summary: Used to retrieve all divisions.
      responses:
        200:
          description: Return all divisions from the database.
          content:
            application/json:
              schema:
                type: array
                items:
                  "$ref": "#/components/schemas/Division"
  /employee:
    get:
      summary: Used to retrieve all employees.
      responses:
        200:
          description: Return all employees from the database.
          content:
            application/json:
              schema:
                type: array
                items:
                  "$ref": "#/components/schemas/Employee"

components:
  schemas:
    Division:
      description: A part of a company.
      type: object
      x-tablename: division
      properties:
        id:
          type: integer
          description: Unique identifier for the division.
          example: 0
          x-primary-key: true
        name:
          type: string
          description: The name of the division.
          example: Engineering
    Employee:
      description: Person that works for a company.
      type: object
      x-tablename: employee
      properties:
        id:
          type: integer
          description: Unique identifier for the employee.
          example: 0
          x-primary-key: true
        name:
          type: string
          description: The name of the employee.
          example: David Andersson
        division:
          allOf:
            - "$ref": "#/components/schemas/Division"
            - nullable: False

The following file uses OpenAlchemy to generate the SQLAlchemy models:

1
2
3
4
5
from open_alchemy import init_yaml

init_yaml(
    "not-nullable-example-spec.yml", models_filename="not_nullable_models_auto.py"
)

The SQLAlchemy models generated by OpenAlchemy are equivalent to the following traditional models file:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()


class Division(Base):
    """Division of a company."""

    __tablename__ = "division"
    id = sa.Column(sa.Integer, primary_key=True)
    name = sa.Column(sa.String)


class Employee(Base):
    """Person that works for a company."""

    __tablename__ = "employee"
    id = sa.Column(sa.Integer, primary_key=True)
    name = sa.Column(sa.String)
    division_id = sa.Column(sa.Integer, sa.ForeignKey("division.id"), nullable=False)

OpenAlchemy will generate the following typed models:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
"""Autogenerated SQLAlchemy models based on OpenAlchemy models."""
# pylint: disable=no-member,super-init-not-called,unused-argument

import typing

import sqlalchemy
from sqlalchemy import orm

from open_alchemy import models

Base = models.Base  # type: ignore


class DivisionDict(typing.TypedDict, total=False):
    """TypedDict for properties that are not required."""

    id: typing.Optional[int]
    name: typing.Optional[str]


class TDivision(typing.Protocol):
    """
    SQLAlchemy model protocol.

    A part of a company.

    Attrs:
        id: Unique identifier for the division.
        name: The name of the division.

    """

    # SQLAlchemy properties
    __table__: sqlalchemy.Table
    __tablename__: str
    query: orm.Query

    # Model properties
    id: "sqlalchemy.Column[typing.Optional[int]]"
    name: "sqlalchemy.Column[typing.Optional[str]]"

    def __init__(
        self, id: typing.Optional[int] = None, name: typing.Optional[str] = None
    ) -> None:
        """
        Construct.

        Args:
            id: Unique identifier for the division.
            name: The name of the division.

        """
        ...

    @classmethod
    def from_dict(
        cls, id: typing.Optional[int] = None, name: typing.Optional[str] = None
    ) -> "TDivision":
        """
        Construct from a dictionary (eg. a POST payload).

        Args:
            id: Unique identifier for the division.
            name: The name of the division.

        Returns:
            Model instance based on the dictionary.

        """
        ...

    @classmethod
    def from_str(cls, value: str) -> "TDivision":
        """
        Construct from a JSON string (eg. a POST payload).

        Returns:
            Model instance based on the JSON string.

        """
        ...

    def to_dict(self) -> DivisionDict:
        """
        Convert to a dictionary (eg. to send back for a GET request).

        Returns:
            Dictionary based on the model instance.

        """
        ...

    def to_str(self) -> str:
        """
        Convert to a JSON string (eg. to send back for a GET request).

        Returns:
            JSON string based on the model instance.

        """
        ...


Division: typing.Type[TDivision] = models.Division  # type: ignore


class EmployeeDict(typing.TypedDict, total=False):
    """TypedDict for properties that are not required."""

    id: typing.Optional[int]
    name: typing.Optional[str]
    division: "DivisionDict"


class TEmployee(typing.Protocol):
    """
    SQLAlchemy model protocol.

    Person that works for a company.

    Attrs:
        id: Unique identifier for the employee.
        name: The name of the employee.
        division: The division of the Employee.

    """

    # SQLAlchemy properties
    __table__: sqlalchemy.Table
    __tablename__: str
    query: orm.Query

    # Model properties
    id: "sqlalchemy.Column[typing.Optional[int]]"
    name: "sqlalchemy.Column[typing.Optional[str]]"
    division: 'sqlalchemy.Column["TDivision"]'

    def __init__(
        self,
        id: typing.Optional[int] = None,
        name: typing.Optional[str] = None,
        division: typing.Optional["TDivision"] = None,
    ) -> None:
        """
        Construct.

        Args:
            id: Unique identifier for the employee.
            name: The name of the employee.
            division: The division of the Employee.

        """
        ...

    @classmethod
    def from_dict(
        cls,
        id: typing.Optional[int] = None,
        name: typing.Optional[str] = None,
        division: typing.Optional["DivisionDict"] = None,
    ) -> "TEmployee":
        """
        Construct from a dictionary (eg. a POST payload).

        Args:
            id: Unique identifier for the employee.
            name: The name of the employee.
            division: The division of the Employee.

        Returns:
            Model instance based on the dictionary.

        """
        ...

    @classmethod
    def from_str(cls, value: str) -> "TEmployee":
        """
        Construct from a JSON string (eg. a POST payload).

        Returns:
            Model instance based on the JSON string.

        """
        ...

    def to_dict(self) -> EmployeeDict:
        """
        Convert to a dictionary (eg. to send back for a GET request).

        Returns:
            Dictionary based on the model instance.

        """
        ...

    def to_str(self) -> str:
        """
        Convert to a JSON string (eg. to send back for a GET request).

        Returns:
            JSON string based on the model instance.

        """
        ...


Employee: typing.Type[TEmployee] = models.Employee  # type: ignore

Backref

SQLAlchemy allows for back references so that the on the child side of the relationship the parent model is also accessible.

See also

Backref

OpenAlchemy documentation for back references.

The following example defines a many to one relationship between Employee and Division that includes a back reference on Division to Employee:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
openapi: "3.0.0"

info:
  title: Test Schema
  description: API to illustrate Many to One Relationships with back references.
  version: "0.1"

paths:
  /division:
    get:
      summary: Used to retrieve all divisions.
      responses:
        200:
          description: Return all divisions from the database.
          content:
            application/json:
              schema:
                type: array
                items:
                  "$ref": "#/components/schemas/Division"
  /employee:
    get:
      summary: Used to retrieve all employees.
      responses:
        200:
          description: Return all employees from the database.
          content:
            application/json:
              schema:
                type: array
                items:
                  "$ref": "#/components/schemas/Employee"

components:
  schemas:
    Division:
      description: A part of a company.
      type: object
      x-tablename: division
      properties:
        id:
          type: integer
          description: Unique identifier for the division.
          example: 0
          x-primary-key: true
        name:
          type: string
          description: The name of the division.
          example: Engineering
    Employee:
      description: Person that works for a company.
      type: object
      x-tablename: employee
      properties:
        id:
          type: integer
          description: Unique identifier for the employee.
          example: 0
          x-primary-key: true
        name:
          type: string
          description: The name of the employee.
          example: David Andersson
        division:
          allOf:
            - "$ref": "#/components/schemas/Division"
            - x-backref: employees

The following file uses OpenAlchemy to generate the SQLAlchemy models:

1
2
3
from open_alchemy import init_yaml

init_yaml("backref-example-spec.yml", models_filename="backref_models_auto.py")

The SQLAlchemy models generated by OpenAlchemy are equivalent to the following traditional models file:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()


class Division(Base):
    """Division of a company."""

    __tablename__ = "division"
    id = sa.Column(sa.Integer, primary_key=True)
    name = sa.Column(sa.String)


class Employee(Base):
    """Person that works for a company."""

    __tablename__ = "employee"
    id = sa.Column(sa.Integer, primary_key=True)
    name = sa.Column(sa.String)
    division = sa.orm.relationship("Division", backref="employees")
    division_id = sa.Column(sa.Integer, sa.ForeignKey("division.id"))

OpenAlchemy will generate the following typed models:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
"""Autogenerated SQLAlchemy models based on OpenAlchemy models."""
# pylint: disable=no-member,super-init-not-called,unused-argument

import typing

import sqlalchemy
from sqlalchemy import orm

from open_alchemy import models

Base = models.Base  # type: ignore


class DivisionDict(typing.TypedDict, total=False):
    """TypedDict for properties that are not required."""

    id: typing.Optional[int]
    name: typing.Optional[str]


class TDivision(typing.Protocol):
    """
    SQLAlchemy model protocol.

    A part of a company.

    Attrs:
        id: Unique identifier for the division.
        name: The name of the division.
        employees: The employees of the Division.

    """

    # SQLAlchemy properties
    __table__: sqlalchemy.Table
    __tablename__: str
    query: orm.Query

    # Model properties
    id: "sqlalchemy.Column[typing.Optional[int]]"
    name: "sqlalchemy.Column[typing.Optional[str]]"
    employees: 'sqlalchemy.Column[typing.Sequence["TEmployee"]]'

    def __init__(
        self,
        id: typing.Optional[int] = None,
        name: typing.Optional[str] = None,
        employees: typing.Optional[typing.Sequence["TEmployee"]] = None,
    ) -> None:
        """
        Construct.

        Args:
            id: Unique identifier for the division.
            name: The name of the division.
            employees: The employees of the Division.

        """
        ...

    @classmethod
    def from_dict(
        cls, id: typing.Optional[int] = None, name: typing.Optional[str] = None
    ) -> "TDivision":
        """
        Construct from a dictionary (eg. a POST payload).

        Args:
            id: Unique identifier for the division.
            name: The name of the division.
            employees: The employees of the Division.

        Returns:
            Model instance based on the dictionary.

        """
        ...

    @classmethod
    def from_str(cls, value: str) -> "TDivision":
        """
        Construct from a JSON string (eg. a POST payload).

        Returns:
            Model instance based on the JSON string.

        """
        ...

    def to_dict(self) -> DivisionDict:
        """
        Convert to a dictionary (eg. to send back for a GET request).

        Returns:
            Dictionary based on the model instance.

        """
        ...

    def to_str(self) -> str:
        """
        Convert to a JSON string (eg. to send back for a GET request).

        Returns:
            JSON string based on the model instance.

        """
        ...


Division: typing.Type[TDivision] = models.Division  # type: ignore


class EmployeeDict(typing.TypedDict, total=False):
    """TypedDict for properties that are not required."""

    id: typing.Optional[int]
    name: typing.Optional[str]
    division: typing.Optional["DivisionDict"]


class TEmployee(typing.Protocol):
    """
    SQLAlchemy model protocol.

    Person that works for a company.

    Attrs:
        id: Unique identifier for the employee.
        name: The name of the employee.
        division: The division of the Employee.

    """

    # SQLAlchemy properties
    __table__: sqlalchemy.Table
    __tablename__: str
    query: orm.Query

    # Model properties
    id: "sqlalchemy.Column[typing.Optional[int]]"
    name: "sqlalchemy.Column[typing.Optional[str]]"
    division: 'sqlalchemy.Column[typing.Optional["TDivision"]]'

    def __init__(
        self,
        id: typing.Optional[int] = None,
        name: typing.Optional[str] = None,
        division: typing.Optional["TDivision"] = None,
    ) -> None:
        """
        Construct.

        Args:
            id: Unique identifier for the employee.
            name: The name of the employee.
            division: The division of the Employee.

        """
        ...

    @classmethod
    def from_dict(
        cls,
        id: typing.Optional[int] = None,
        name: typing.Optional[str] = None,
        division: typing.Optional["DivisionDict"] = None,
    ) -> "TEmployee":
        """
        Construct from a dictionary (eg. a POST payload).

        Args:
            id: Unique identifier for the employee.
            name: The name of the employee.
            division: The division of the Employee.

        Returns:
            Model instance based on the dictionary.

        """
        ...

    @classmethod
    def from_str(cls, value: str) -> "TEmployee":
        """
        Construct from a JSON string (eg. a POST payload).

        Returns:
            Model instance based on the JSON string.

        """
        ...

    def to_dict(self) -> EmployeeDict:
        """
        Convert to a dictionary (eg. to send back for a GET request).

        Returns:
            Dictionary based on the model instance.

        """
        ...

    def to_str(self) -> str:
        """
        Convert to a JSON string (eg. to send back for a GET request).

        Returns:
            JSON string based on the model instance.

        """
        ...


Employee: typing.Type[TEmployee] = models.Employee  # type: ignore

Custom Foreign Key Column

By default, OpenAlchemy will pick the id property to construct the underlying foreign key constraint for a relationship. This can be changed using the x-foreign-key-column extension property.

See also

Custom Foreign Key

OpenAlchemy documentation for custom foreign key columns.

The following example defines a many to one relationship between Employee and Division where the name column is used instead of the id column to construct the foreign key:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
openapi: "3.0.0"

info:
  title: Test Schema
  description: API to illustrate Many to One Relationships with custom foreign keys.
  version: "0.1"

paths:
  /division:
    get:
      summary: Used to retrieve all divisions.
      responses:
        200:
          description: Return all divisions from the database.
          content:
            application/json:
              schema:
                type: array
                items:
                  "$ref": "#/components/schemas/Division"
  /employee:
    get:
      summary: Used to retrieve all employees.
      responses:
        200:
          description: Return all employees from the database.
          content:
            application/json:
              schema:
                type: array
                items:
                  "$ref": "#/components/schemas/Employee"

components:
  schemas:
    Division:
      description: A part of a company.
      type: object
      x-tablename: division
      properties:
        id:
          type: integer
          description: Unique identifier for the division.
          example: 0
          x-primary-key: true
        name:
          type: string
          description: The name of the division.
          example: Engineering.
    Employee:
      description: Person that works for a company.
      type: object
      x-tablename: employee
      properties:
        id:
          type: integer
          description: Unique identifier for the employee.
          example: 0
          x-primary-key: true
        name:
          type: string
          description: The name of the employee.
          example: David Andersson
        division:
          allOf:
            - "$ref": "#/components/schemas/Division"
            - x-foreign-key-column: name

The following file uses OpenAlchemy to generate the SQLAlchemy models:

1
2
3
4
5
6
from open_alchemy import init_yaml

init_yaml(
    "custom-foreign-key-example-spec.yml",
    models_filename="custom_foreign_key_models_auto.py",
)

OpenAlchemy will generate the following typed models:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
"""Autogenerated SQLAlchemy models based on OpenAlchemy models."""
# pylint: disable=no-member,super-init-not-called,unused-argument

import typing

import sqlalchemy
from sqlalchemy import orm

from open_alchemy import models

Base = models.Base  # type: ignore


class DivisionDict(typing.TypedDict, total=False):
    """TypedDict for properties that are not required."""

    id: typing.Optional[int]
    name: typing.Optional[str]


class TDivision(typing.Protocol):
    """
    SQLAlchemy model protocol.

    A part of a company.

    Attrs:
        id: Unique identifier for the division.
        name: The name of the division.

    """

    # SQLAlchemy properties
    __table__: sqlalchemy.Table
    __tablename__: str
    query: orm.Query

    # Model properties
    id: "sqlalchemy.Column[typing.Optional[int]]"
    name: "sqlalchemy.Column[typing.Optional[str]]"

    def __init__(
        self, id: typing.Optional[int] = None, name: typing.Optional[str] = None
    ) -> None:
        """
        Construct.

        Args:
            id: Unique identifier for the division.
            name: The name of the division.

        """
        ...

    @classmethod
    def from_dict(
        cls, id: typing.Optional[int] = None, name: typing.Optional[str] = None
    ) -> "TDivision":
        """
        Construct from a dictionary (eg. a POST payload).

        Args:
            id: Unique identifier for the division.
            name: The name of the division.

        Returns:
            Model instance based on the dictionary.

        """
        ...

    @classmethod
    def from_str(cls, value: str) -> "TDivision":
        """
        Construct from a JSON string (eg. a POST payload).

        Returns:
            Model instance based on the JSON string.

        """
        ...

    def to_dict(self) -> DivisionDict:
        """
        Convert to a dictionary (eg. to send back for a GET request).

        Returns:
            Dictionary based on the model instance.

        """
        ...

    def to_str(self) -> str:
        """
        Convert to a JSON string (eg. to send back for a GET request).

        Returns:
            JSON string based on the model instance.

        """
        ...


Division: typing.Type[TDivision] = models.Division  # type: ignore


class EmployeeDict(typing.TypedDict, total=False):
    """TypedDict for properties that are not required."""

    id: typing.Optional[int]
    name: typing.Optional[str]
    division: typing.Optional["DivisionDict"]


class TEmployee(typing.Protocol):
    """
    SQLAlchemy model protocol.

    Person that works for a company.

    Attrs:
        id: Unique identifier for the employee.
        name: The name of the employee.
        division: The division of the Employee.

    """

    # SQLAlchemy properties
    __table__: sqlalchemy.Table
    __tablename__: str
    query: orm.Query

    # Model properties
    id: "sqlalchemy.Column[typing.Optional[int]]"
    name: "sqlalchemy.Column[typing.Optional[str]]"
    division: 'sqlalchemy.Column[typing.Optional["TDivision"]]'

    def __init__(
        self,
        id: typing.Optional[int] = None,
        name: typing.Optional[str] = None,
        division: typing.Optional["TDivision"] = None,
    ) -> None:
        """
        Construct.

        Args:
            id: Unique identifier for the employee.
            name: The name of the employee.
            division: The division of the Employee.

        """
        ...

    @classmethod
    def from_dict(
        cls,
        id: typing.Optional[int] = None,
        name: typing.Optional[str] = None,
        division: typing.Optional["DivisionDict"] = None,
    ) -> "TEmployee":
        """
        Construct from a dictionary (eg. a POST payload).

        Args:
            id: Unique identifier for the employee.
            name: The name of the employee.
            division: The division of the Employee.

        Returns:
            Model instance based on the dictionary.

        """
        ...

    @classmethod
    def from_str(cls, value: str) -> "TEmployee":
        """
        Construct from a JSON string (eg. a POST payload).

        Returns:
            Model instance based on the JSON string.

        """
        ...

    def to_dict(self) -> EmployeeDict:
        """
        Convert to a dictionary (eg. to send back for a GET request).

        Returns:
            Dictionary based on the model instance.

        """
        ...

    def to_str(self) -> str:
        """
        Convert to a JSON string (eg. to send back for a GET request).

        Returns:
            JSON string based on the model instance.

        """
        ...


Employee: typing.Type[TEmployee] = models.Employee  # type: ignore

Relationship kwargs

There are a range of keyword arguments for the relationship in SQLAlchemy for a range of use cases. OpenAlchemy supports these using the x-kwargs extension property that can be defined along with an object or array reference.

See also

Other Keyword Arguments

OpenAlchemy documentation for relationship keyword arguments.

SQLAlchemy Relationship API

Documentation of the SQLAlchemy relationship API.

The following example defines the order_by keyword argument for the relationship between Employee and Division:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
openapi: "3.0.0"

info:
  title: Test Schema
  description: API to illustrate Many to One Relationships with keyword arguments.
  version: "0.1"

paths:
  /division:
    get:
      summary: Used to retrieve all divisions.
      responses:
        200:
          description: Return all divisions from the database.
          content:
            application/json:
              schema:
                type: array
                items:
                  "$ref": "#/components/schemas/Division"
  /employee:
    get:
      summary: Used to retrieve all employees.
      responses:
        200:
          description: Return all employees from the database.
          content:
            application/json:
              schema:
                type: array
                items:
                  "$ref": "#/components/schemas/Employee"

components:
  schemas:
    Division:
      description: A part of a company.
      type: object
      x-tablename: division
      properties:
        id:
          type: integer
          description: Unique identifier for the division.
          example: 0
          x-primary-key: true
        name:
          type: string
          description: The name of the division.
          example: Engineering
    Employee:
      description: Person that works for a company.
      type: object
      x-tablename: employee
      properties:
        id:
          type: integer
          description: Unique identifier for the employee.
          example: 0
          x-primary-key: true
        name:
          type: string
          description: The name of the employee.
          example: David Andersson
        division:
          allOf:
            - "$ref": "#/components/schemas/Division"
            - x-kwargs:
                order_by: Division.name

The following file uses OpenAlchemy to generate the SQLAlchemy models:

1
2
3
from open_alchemy import init_yaml

init_yaml("kwargs-example-spec.yml", models_filename="kwargs_models_auto.py")

The SQLAlchemy models generated by OpenAlchemy are equivalent to the following traditional models file:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()


class Division(Base):
    """Division of a company."""

    __tablename__ = "division"
    id = sa.Column(sa.Integer, primary_key=True)
    name = sa.Column(sa.String)


class Employee(Base):
    """Person that works for a company."""

    __tablename__ = "employee"
    id = sa.Column(sa.Integer, primary_key=True)
    name = sa.Column(sa.String)
    division = sa.orm.relationship("Division", order_by="Division.name")
    division_id = sa.Column(sa.Integer, sa.ForeignKey("division.id"))

OpenAlchemy will generate the following typed models:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
"""Autogenerated SQLAlchemy models based on OpenAlchemy models."""
# pylint: disable=no-member,super-init-not-called,unused-argument

import typing

import sqlalchemy
from sqlalchemy import orm

from open_alchemy import models

Base = models.Base  # type: ignore


class DivisionDict(typing.TypedDict, total=False):
    """TypedDict for properties that are not required."""

    id: typing.Optional[int]
    name: typing.Optional[str]


class TDivision(typing.Protocol):
    """
    SQLAlchemy model protocol.

    A part of a company.

    Attrs:
        id: Unique identifier for the division.
        name: The name of the division.

    """

    # SQLAlchemy properties
    __table__: sqlalchemy.Table
    __tablename__: str
    query: orm.Query

    # Model properties
    id: "sqlalchemy.Column[typing.Optional[int]]"
    name: "sqlalchemy.Column[typing.Optional[str]]"

    def __init__(
        self, id: typing.Optional[int] = None, name: typing.Optional[str] = None
    ) -> None:
        """
        Construct.

        Args:
            id: Unique identifier for the division.
            name: The name of the division.

        """
        ...

    @classmethod
    def from_dict(
        cls, id: typing.Optional[int] = None, name: typing.Optional[str] = None
    ) -> "TDivision":
        """
        Construct from a dictionary (eg. a POST payload).

        Args:
            id: Unique identifier for the division.
            name: The name of the division.

        Returns:
            Model instance based on the dictionary.

        """
        ...

    @classmethod
    def from_str(cls, value: str) -> "TDivision":
        """
        Construct from a JSON string (eg. a POST payload).

        Returns:
            Model instance based on the JSON string.

        """
        ...

    def to_dict(self) -> DivisionDict:
        """
        Convert to a dictionary (eg. to send back for a GET request).

        Returns:
            Dictionary based on the model instance.

        """
        ...

    def to_str(self) -> str:
        """
        Convert to a JSON string (eg. to send back for a GET request).

        Returns:
            JSON string based on the model instance.

        """
        ...


Division: typing.Type[TDivision] = models.Division  # type: ignore


class EmployeeDict(typing.TypedDict, total=False):
    """TypedDict for properties that are not required."""

    id: typing.Optional[int]
    name: typing.Optional[str]
    division: typing.Optional["DivisionDict"]


class TEmployee(typing.Protocol):
    """
    SQLAlchemy model protocol.

    Person that works for a company.

    Attrs:
        id: Unique identifier for the employee.
        name: The name of the employee.
        division: The division of the Employee.

    """

    # SQLAlchemy properties
    __table__: sqlalchemy.Table
    __tablename__: str
    query: orm.Query

    # Model properties
    id: "sqlalchemy.Column[typing.Optional[int]]"
    name: "sqlalchemy.Column[typing.Optional[str]]"
    division: 'sqlalchemy.Column[typing.Optional["TDivision"]]'

    def __init__(
        self,
        id: typing.Optional[int] = None,
        name: typing.Optional[str] = None,
        division: typing.Optional["TDivision"] = None,
    ) -> None:
        """
        Construct.

        Args:
            id: Unique identifier for the employee.
            name: The name of the employee.
            division: The division of the Employee.

        """
        ...

    @classmethod
    def from_dict(
        cls,
        id: typing.Optional[int] = None,
        name: typing.Optional[str] = None,
        division: typing.Optional["DivisionDict"] = None,
    ) -> "TEmployee":
        """
        Construct from a dictionary (eg. a POST payload).

        Args:
            id: Unique identifier for the employee.
            name: The name of the employee.
            division: The division of the Employee.

        Returns:
            Model instance based on the dictionary.

        """
        ...

    @classmethod
    def from_str(cls, value: str) -> "TEmployee":
        """
        Construct from a JSON string (eg. a POST payload).

        Returns:
            Model instance based on the JSON string.

        """
        ...

    def to_dict(self) -> EmployeeDict:
        """
        Convert to a dictionary (eg. to send back for a GET request).

        Returns:
            Dictionary based on the model instance.

        """
        ...

    def to_str(self) -> str:
        """
        Convert to a JSON string (eg. to send back for a GET request).

        Returns:
            JSON string based on the model instance.

        """
        ...


Employee: typing.Type[TEmployee] = models.Employee  # type: ignore