Many to Many

The many to many relationship is used when a parent model can have many children but the child can also have many parents. For example, an employee could be working on multiple projects and multiple employees are generally assigned to a project.

See also

Many to Many

OpenAlchemy documentation for many to many relationships.

SQLAlchemy Many to Many

SQLAlchemy documentation for many to many relationships.

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

 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
openapi: "3.0.0"

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

paths:
  /project:
    get:
      summary: Used to retrieve all projects.
      responses:
        200:
          description: Return all projects from the database.
          content:
            application/json:
              schema:
                type: array
                items:
                  "$ref": "#/components/schemas/Project"
  /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:
    Project:
      description: A large sized business objective.
      type: object
      x-tablename: project
      properties:
        id:
          type: integer
          description: Unique identifier for the project.
          example: 0
          x-primary-key: true
        name:
          type: string
          description: The name of the project.
          example: Expand to the USA
    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
        projects:
          type: array
          items:
            allOf:
              - "$ref": "#/components/schemas/Project"
              - x-secondary: employee_project
          description: The projects the employee is working on.

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
23
24
25
26
27
28
29
import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()


employee_project = sa.Table(
    "employee_project",
    Base.metadata,
    sa.Column("project_id", sa.Integer, sa.ForeignKey("project.id")),
    sa.Column("employee_id", sa.Integer, sa.ForeignKey("employee.id")),
)


class Project(Base):
    """A large sized business objective."""

    __tablename__ = "project"
    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)
    projects = sa.orm.relationship("Project", secondary="project_employee")

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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
"""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 ProjectDict(typing.TypedDict, total=False):
    """TypedDict for properties that are not required."""

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


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

    A large sized business objective.

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

    """

    # 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 project.
            name: The name of the project.

        """
        ...

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

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

        Returns:
            Model instance based on the dictionary.

        """
        ...

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

        Returns:
            Model instance based on the JSON string.

        """
        ...

    def to_dict(self) -> ProjectDict:
        """
        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.

        """
        ...


Project: typing.Type[TProject] = models.Project  # type: ignore


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

    id: typing.Optional[int]
    name: typing.Optional[str]
    projects: typing.Sequence["ProjectDict"]


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.
        projects: The projects the employee is working on.

    """

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

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

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

        Args:
            id: Unique identifier for the employee.
            name: The name of the employee.
            projects: The projects the employee is working on.

        """
        ...

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

        Args:
            id: Unique identifier for the employee.
            name: The name of the employee.
            projects: The projects the employee is working on.

        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


class EmployeeProjectDict(typing.TypedDict, total=True):
    """TypedDict for properties that are required."""

    employee_id: int
    project_id: int


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

    Attrs:
        employee_id: The employee_id of the EmployeeProject.
        project_id: The project_id of the EmployeeProject.

    """

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

    # Model properties
    employee_id: "sqlalchemy.Column[int]"
    project_id: "sqlalchemy.Column[int]"

    def __init__(self, employee_id: int, project_id: int) -> None:
        """
        Construct.

        Args:
            employee_id: The employee_id of the EmployeeProject.
            project_id: The project_id of the EmployeeProject.

        """
        ...

    @classmethod
    def from_dict(cls, employee_id: int, project_id: int) -> "TEmployeeProject":
        """
        Construct from a dictionary (eg. a POST payload).

        Args:
            employee_id: The employee_id of the EmployeeProject.
            project_id: The project_id of the EmployeeProject.

        Returns:
            Model instance based on the dictionary.

        """
        ...

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

        Returns:
            Model instance based on the JSON string.

        """
        ...

    def to_dict(self) -> EmployeeProjectDict:
        """
        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.

        """
        ...


EmployeeProject: typing.Type[TEmployeeProject] = models.EmployeeProject  # type: ignore

Custom Association Schema

OpenAlchemy also supports customization of the association schema that implements the many-to-many relationship. This means that the schema can be changed to include, for example, a column tracking when the association was established.

See also

Custom Association Schema

OpenAlchemy documentation for many to many relationships with a custom association schema.

The following example defines a schema for the association:

 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
openapi: "3.0.0"

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

paths:
  /project:
    get:
      summary: Used to retrieve all projects.
      responses:
        200:
          description: Return all projects from the database.
          content:
            application/json:
              schema:
                type: array
                items:
                  "$ref": "#/components/schemas/Project"
  /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:
    Project:
      description: A large sized business objective.
      type: object
      x-tablename: project
      properties:
        id:
          type: integer
          description: Unique identifier for the project.
          example: 0
          x-primary-key: true
        name:
          type: string
          description: The name of the project.
          example: Expand to the USA
    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
        projects:
          type: array
          items:
            allOf:
              - "$ref": "#/components/schemas/Project"
              - x-secondary: employee_project
          description: The projects the employee is working on.
    EmployeeProject:
      type: object
      x-tablename: employee_project
      properties:
        employee_id:
          type: integer
          x-primary-key: true
          x-foreign-key: employee.id
        project_id:
          type: integer
          x-primary-key: true
          x-foreign-key: project.id
      required:
        - employee_id
        - project_id

The following file uses OpenAlchemy to generate the SQLAlchemy models:

1
2
3
from open_alchemy import init_yaml

init_yaml("pre-defined-example-spec.yml", models_filename="pre_defined_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
23
24
25
26
27
28
29
import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()


class Project(Base):
    """A large sized business objective."""

    __tablename__ = "project"
    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)
    projects = sa.orm.relationship("Project", secondary="project_employee")


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

    __tablename__ = "project_employee"
    employee_id = sa.Column(sa.Integer, sa.ForeignKey("employee.id"), primary_key=True)
    employee_id = sa.Column(sa.Integer, sa.ForeignKey("project.id"), primary_key=True)

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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
"""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 ProjectDict(typing.TypedDict, total=False):
    """TypedDict for properties that are not required."""

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


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

    A large sized business objective.

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

    """

    # 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 project.
            name: The name of the project.

        """
        ...

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

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

        Returns:
            Model instance based on the dictionary.

        """
        ...

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

        Returns:
            Model instance based on the JSON string.

        """
        ...

    def to_dict(self) -> ProjectDict:
        """
        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.

        """
        ...


Project: typing.Type[TProject] = models.Project  # type: ignore


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

    id: typing.Optional[int]
    name: typing.Optional[str]
    projects: typing.Sequence["ProjectDict"]


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.
        projects: The projects the employee is working on.

    """

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

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

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

        Args:
            id: Unique identifier for the employee.
            name: The name of the employee.
            projects: The projects the employee is working on.

        """
        ...

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

        Args:
            id: Unique identifier for the employee.
            name: The name of the employee.
            projects: The projects the employee is working on.

        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


class EmployeeProjectDict(typing.TypedDict, total=True):
    """TypedDict for properties that are required."""

    employee_id: int
    project_id: int


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

    Attrs:
        employee_id: The employee_id of the EmployeeProject.
        project_id: The project_id of the EmployeeProject.

    """

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

    # Model properties
    employee_id: "sqlalchemy.Column[int]"
    project_id: "sqlalchemy.Column[int]"

    def __init__(self, employee_id: int, project_id: int) -> None:
        """
        Construct.

        Args:
            employee_id: The employee_id of the EmployeeProject.
            project_id: The project_id of the EmployeeProject.

        """
        ...

    @classmethod
    def from_dict(cls, employee_id: int, project_id: int) -> "TEmployeeProject":
        """
        Construct from a dictionary (eg. a POST payload).

        Args:
            employee_id: The employee_id of the EmployeeProject.
            project_id: The project_id of the EmployeeProject.

        Returns:
            Model instance based on the dictionary.

        """
        ...

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

        Returns:
            Model instance based on the JSON string.

        """
        ...

    def to_dict(self) -> EmployeeProjectDict:
        """
        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.

        """
        ...


EmployeeProject: typing.Type[TEmployeeProject] = models.EmployeeProject  # type: ignore