Skip to content

primary_key

Primary key of a model: which fields form it, their database columns, and how to read, write, bind and compare its value.

Every consumer of a model's key goes through this object instead of a single primary key field name, so the same code serves single-column keys and (later) keys spanning several columns.

CompositeKey

Bases: PrimaryKey

Primary key spanning several columns, whose value is a tuple of the parts in key order.

Source code in ormar/models/primary_key.py
Python
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
class CompositeKey(PrimaryKey):
    """
    Primary key spanning several columns, whose value is a tuple of the parts
    in key order.
    """

    @property
    def is_composite(self) -> bool:
        """
        :return: always ``True``
        :rtype: bool
        """
        return True

    @property
    def autoincrement(self) -> bool:
        """
        :return: always ``False``, no part of a composite key is generated by
            the database (field objects may be shared with sibling models
            inheriting them, so the rule lives on the key)
        :rtype: bool
        """
        return False

    def python_type(self) -> Any:
        """
        :return: ``tuple``
        :rtype: Any
        """
        return tuple

    def value(self, instance: "NewBaseModel") -> Any:
        """
        :param instance: model instance
        :type instance: NewBaseModel
        :return: tuple of the key parts, ``None`` when any part is not set
        :rtype: Any
        """
        return self.value_from(data=instance.__dict__)

    def value_from(self, data: Mapping[str, Any]) -> Any:
        """
        :param data: values by field name (e.g. a model dict)
        :type data: Mapping[str, Any]
        :return: tuple of the key parts, ``None`` when any part is not set
        :rtype: Any
        """
        if self.layout().simple:
            parts = tuple(
                self.part_value(field=field, value=data.get(field))
                for field in self.fields
            )
        else:
            parts = self.column_parts(data=data)
        return None if None in parts else parts

    def flat_parts(self, value: Any) -> tuple[Any, ...]:
        """
        Turn a key value given as a tuple/list of the key columns or as a dict
        of exactly the key fields into the raw value of each key column
        (related models in relation parts replaced by the values they are
        referenced by).

        :raises QueryDefinitionError: if the value does not match the key or a
            column gets a tuple, list, dict or model instead of a single value
        :param value: key value
        :type value: Any
        :return: the value of each key column, in key order
        :rtype: tuple[Any, ...]
        """
        parts = self.split_value(value=value)
        if not_scalar(parts=parts):
            raise self.mismatch_error(value=value)
        return parts

    def split_value(self, value: Any) -> tuple[Any, ...]:
        """
        ``flat_parts`` without checking that each column gets a single value,
        for key values ormar built itself (e.g. a model's ``pk``).

        :raises QueryDefinitionError: if the value does not match the key
        :param value: key value
        :type value: Any
        :return: the value of each key column, in key order
        :rtype: tuple[Any, ...]
        """
        if isinstance(value, dict) and set(value) == set(self.fields):
            for field, part in value.items():
                if isinstance(part, (tuple, list)) and len(part) != len(
                    self.owner.ormar_config.model_fields[field].column_aliases()
                ):
                    raise self.mismatch_error(value=value)
            return self.column_parts(data=value)
        layout = self.layout()
        if isinstance(value, (tuple, list)) and len(value) == len(layout.column_fields):
            model_fields = self.owner.ormar_config.model_fields
            return tuple(
                self.part_value(field=field, value=part)
                if len(model_fields[field].column_aliases()) == 1
                else part
                for field, part in zip(layout.column_fields, value)
            )
        raise self.mismatch_error(value=value)

    def mismatch_error(self, value: Any) -> QueryDefinitionError:
        """
        :param value: key value that doesn't match the key
        :type value: Any
        :return: error describing the expected key value
        :rtype: QueryDefinitionError
        """
        return QueryDefinitionError(
            f"{self.owner.__name__} primary key has fields {self.fields} "
            f"(columns {self.column_aliases()}), got {value!r}; give one value "
            "per column"
        )

    def to_dict(self, value: Any) -> dict[str, Any]:
        """
        Split a key value given as a tuple/list of the key columns or as a dict
        of exactly the key fields into the value of each key field: a foreign
        key stored in several columns gets the tuple of its columns.

        :raises QueryDefinitionError: if the value does not match the key
        :param value: key value
        :type value: Any
        :return: key parts by field name
        :rtype: dict[str, Any]
        """
        by_column = dict(zip(self.column_aliases(), self.flat_parts(value=value)))
        model_fields = self.owner.ormar_config.model_fields
        return {
            field: key_value(
                parts=tuple(
                    by_column[column] for column in model_fields[field].column_aliases()
                )
            )
            for field in self.fields
        }

    def getter(self, keys: tuple[str, ...]) -> Callable[[Mapping[str, Any]], Any]:
        """
        :param keys: names under which the key parts are stored, in key order
        :type keys: tuple[str, ...]
        :return: reader returning the key tuple or ``None``
        :rtype: Callable[[Mapping[str, Any]], Any]
        """
        return CompositeKeyGetter(keys=keys)

    def slot_names(self, count: int) -> tuple[str, ...]:
        """
        :param count: number of key columns
        :type count: int
        :return: ``ormar_pk_0``, ``ormar_pk_1``, ... one per key column
        :rtype: tuple[str, ...]
        """
        return tuple(f"{PK_SLOT}_{index}" for index in range(count))

    def bind_params(self, value: Any) -> dict[str, Any]:
        """
        :param value: key value
        :type value: Any
        :return: parameters binding the parts to ``bind_slots()``
        :rtype: dict[str, Any]
        """
        return dict(zip(self.layout().bind_slots, self.split_value(value=value)))

autoincrement property

Returns:

Type Description
bool

always False, no part of a composite key is generated by the database (field objects may be shared with sibling models inheriting them, so the rule lives on the key)

is_composite property

Returns:

Type Description
bool

always True

bind_params(value)

Parameters:

Name Type Description Default
value Any

key value

required

Returns:

Type Description
dict[str, Any]

parameters binding the parts to bind_slots()

Source code in ormar/models/primary_key.py
Python
676
677
678
679
680
681
682
683
def bind_params(self, value: Any) -> dict[str, Any]:
    """
    :param value: key value
    :type value: Any
    :return: parameters binding the parts to ``bind_slots()``
    :rtype: dict[str, Any]
    """
    return dict(zip(self.layout().bind_slots, self.split_value(value=value)))

flat_parts(value)

Turn a key value given as a tuple/list of the key columns or as a dict of exactly the key fields into the raw value of each key column (related models in relation parts replaced by the values they are referenced by).

Parameters:

Name Type Description Default
value Any

key value

required

Returns:

Type Description
tuple[Any, ...]

the value of each key column, in key order

Raises:

Type Description
QueryDefinitionError

if the value does not match the key or a column gets a tuple, list, dict or model instead of a single value

Source code in ormar/models/primary_key.py
Python
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
def flat_parts(self, value: Any) -> tuple[Any, ...]:
    """
    Turn a key value given as a tuple/list of the key columns or as a dict
    of exactly the key fields into the raw value of each key column
    (related models in relation parts replaced by the values they are
    referenced by).

    :raises QueryDefinitionError: if the value does not match the key or a
        column gets a tuple, list, dict or model instead of a single value
    :param value: key value
    :type value: Any
    :return: the value of each key column, in key order
    :rtype: tuple[Any, ...]
    """
    parts = self.split_value(value=value)
    if not_scalar(parts=parts):
        raise self.mismatch_error(value=value)
    return parts

getter(keys)

Parameters:

Name Type Description Default
keys tuple[str, ...]

names under which the key parts are stored, in key order

required

Returns:

Type Description
Callable[[Mapping[str, Any]], Any]

reader returning the key tuple or None

Source code in ormar/models/primary_key.py
Python
658
659
660
661
662
663
664
665
def getter(self, keys: tuple[str, ...]) -> Callable[[Mapping[str, Any]], Any]:
    """
    :param keys: names under which the key parts are stored, in key order
    :type keys: tuple[str, ...]
    :return: reader returning the key tuple or ``None``
    :rtype: Callable[[Mapping[str, Any]], Any]
    """
    return CompositeKeyGetter(keys=keys)

mismatch_error(value)

Parameters:

Name Type Description Default
value Any

key value that doesn't match the key

required

Returns:

Type Description
QueryDefinitionError

error describing the expected key value

Source code in ormar/models/primary_key.py
Python
622
623
624
625
626
627
628
629
630
631
632
633
def mismatch_error(self, value: Any) -> QueryDefinitionError:
    """
    :param value: key value that doesn't match the key
    :type value: Any
    :return: error describing the expected key value
    :rtype: QueryDefinitionError
    """
    return QueryDefinitionError(
        f"{self.owner.__name__} primary key has fields {self.fields} "
        f"(columns {self.column_aliases()}), got {value!r}; give one value "
        "per column"
    )

python_type()

Returns:

Type Description
Any

tuple

Source code in ormar/models/primary_key.py
Python
542
543
544
545
546
547
def python_type(self) -> Any:
    """
    :return: ``tuple``
    :rtype: Any
    """
    return tuple

slot_names(count)

Parameters:

Name Type Description Default
count int

number of key columns

required

Returns:

Type Description
tuple[str, ...]

ormar_pk_0, ormar_pk_1, ... one per key column

Source code in ormar/models/primary_key.py
Python
667
668
669
670
671
672
673
674
def slot_names(self, count: int) -> tuple[str, ...]:
    """
    :param count: number of key columns
    :type count: int
    :return: ``ormar_pk_0``, ``ormar_pk_1``, ... one per key column
    :rtype: tuple[str, ...]
    """
    return tuple(f"{PK_SLOT}_{index}" for index in range(count))

split_value(value)

flat_parts without checking that each column gets a single value, for key values ormar built itself (e.g. a model's pk).

Parameters:

Name Type Description Default
value Any

key value

required

Returns:

Type Description
tuple[Any, ...]

the value of each key column, in key order

Raises:

Type Description
QueryDefinitionError

if the value does not match the key

Source code in ormar/models/primary_key.py
Python
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
def split_value(self, value: Any) -> tuple[Any, ...]:
    """
    ``flat_parts`` without checking that each column gets a single value,
    for key values ormar built itself (e.g. a model's ``pk``).

    :raises QueryDefinitionError: if the value does not match the key
    :param value: key value
    :type value: Any
    :return: the value of each key column, in key order
    :rtype: tuple[Any, ...]
    """
    if isinstance(value, dict) and set(value) == set(self.fields):
        for field, part in value.items():
            if isinstance(part, (tuple, list)) and len(part) != len(
                self.owner.ormar_config.model_fields[field].column_aliases()
            ):
                raise self.mismatch_error(value=value)
        return self.column_parts(data=value)
    layout = self.layout()
    if isinstance(value, (tuple, list)) and len(value) == len(layout.column_fields):
        model_fields = self.owner.ormar_config.model_fields
        return tuple(
            self.part_value(field=field, value=part)
            if len(model_fields[field].column_aliases()) == 1
            else part
            for field, part in zip(layout.column_fields, value)
        )
    raise self.mismatch_error(value=value)

to_dict(value)

Split a key value given as a tuple/list of the key columns or as a dict of exactly the key fields into the value of each key field: a foreign key stored in several columns gets the tuple of its columns.

Parameters:

Name Type Description Default
value Any

key value

required

Returns:

Type Description
dict[str, Any]

key parts by field name

Raises:

Type Description
QueryDefinitionError

if the value does not match the key

Source code in ormar/models/primary_key.py
Python
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
def to_dict(self, value: Any) -> dict[str, Any]:
    """
    Split a key value given as a tuple/list of the key columns or as a dict
    of exactly the key fields into the value of each key field: a foreign
    key stored in several columns gets the tuple of its columns.

    :raises QueryDefinitionError: if the value does not match the key
    :param value: key value
    :type value: Any
    :return: key parts by field name
    :rtype: dict[str, Any]
    """
    by_column = dict(zip(self.column_aliases(), self.flat_parts(value=value)))
    model_fields = self.owner.ormar_config.model_fields
    return {
        field: key_value(
            parts=tuple(
                by_column[column] for column in model_fields[field].column_aliases()
            )
        )
        for field in self.fields
    }

value(instance)

Parameters:

Name Type Description Default
instance NewBaseModel

model instance

required

Returns:

Type Description
Any

tuple of the key parts, None when any part is not set

Source code in ormar/models/primary_key.py
Python
549
550
551
552
553
554
555
556
def value(self, instance: "NewBaseModel") -> Any:
    """
    :param instance: model instance
    :type instance: NewBaseModel
    :return: tuple of the key parts, ``None`` when any part is not set
    :rtype: Any
    """
    return self.value_from(data=instance.__dict__)

value_from(data)

Parameters:

Name Type Description Default
data Mapping[str, Any]

values by field name (e.g. a model dict)

required

Returns:

Type Description
Any

tuple of the key parts, None when any part is not set

Source code in ormar/models/primary_key.py
Python
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
def value_from(self, data: Mapping[str, Any]) -> Any:
    """
    :param data: values by field name (e.g. a model dict)
    :type data: Mapping[str, Any]
    :return: tuple of the key parts, ``None`` when any part is not set
    :rtype: Any
    """
    if self.layout().simple:
        parts = tuple(
            self.part_value(field=field, value=data.get(field))
            for field in self.fields
        )
    else:
        parts = self.column_parts(data=data)
    return None if None in parts else parts

CompositeKeyGetter

Reads a composite key out of a mapping: a tuple of the parts, or None when any part is None.

Source code in ormar/models/primary_key.py
Python
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
class CompositeKeyGetter:
    """
    Reads a composite key out of a mapping: a tuple of the parts, or ``None``
    when any part is ``None``.
    """

    __slots__ = ("read",)

    def __init__(self, *, keys: tuple[str, ...]) -> None:
        """
        :param keys: names under which the key parts are stored, in key order
        :type keys: tuple[str, ...]
        """
        self.read = operator.itemgetter(*keys)

    def __call__(self, data: Mapping[str, Any]) -> Any:
        """
        :param data: mapping holding the key parts
        :type data: Mapping[str, Any]
        :return: tuple of the parts, ``None`` when any part is ``None``
        :rtype: Any
        """
        parts = self.read(data)
        return None if None in parts else parts

__call__(data)

Parameters:

Name Type Description Default
data Mapping[str, Any]

mapping holding the key parts

required

Returns:

Type Description
Any

tuple of the parts, None when any part is None

Source code in ormar/models/primary_key.py
Python
507
508
509
510
511
512
513
514
515
def __call__(self, data: Mapping[str, Any]) -> Any:
    """
    :param data: mapping holding the key parts
    :type data: Mapping[str, Any]
    :return: tuple of the parts, ``None`` when any part is ``None``
    :rtype: Any
    """
    parts = self.read(data)
    return None if None in parts else parts

__init__(*, keys)

Parameters:

Name Type Description Default
keys tuple[str, ...]

names under which the key parts are stored, in key order

required
Source code in ormar/models/primary_key.py
Python
500
501
502
503
504
505
def __init__(self, *, keys: tuple[str, ...]) -> None:
    """
    :param keys: names under which the key parts are stored, in key order
    :type keys: tuple[str, ...]
    """
    self.read = operator.itemgetter(*keys)

KeyLayout dataclass

The columns of a primary key, resolved once (and again after the owner's column caches are reset, e.g. when forward references resolve).

Attributes:

Name Type Description
key PrimaryKey

primary key the layout belongs to

column_aliases tuple[str, ...]

database column names in key order

column_fields tuple[str, ...]

per key column, the first key field storing it

simple bool

whether every key field stores exactly one column of its own (no foreign key of several columns, no shared column), so the key value has one part per key field

bind_slots tuple[str, ...]

names of the bind parameters of the key columns

Source code in ormar/models/primary_key.py
Python
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
@dataclass(frozen=True)
class KeyLayout:
    """
    The columns of a primary key, resolved once (and again after the owner's
    column caches are reset, e.g. when forward references resolve).

    :ivar key: primary key the layout belongs to
    :ivar column_aliases: database column names in key order
    :ivar column_fields: per key column, the first key field storing it
    :ivar simple: whether every key field stores exactly one column of its
        own (no foreign key of several columns, no shared column), so the
        key value has one part per key field
    :ivar bind_slots: names of the bind parameters of the key columns
    """

    key: "PrimaryKey"
    column_aliases: tuple[str, ...]
    column_fields: tuple[str, ...]
    simple: bool
    bind_slots: tuple[str, ...]

PrimaryKey

Bases: ABC

Primary key of a model class.

Column names are resolved from the owner once (layout) and cached until the owner's column caches are reset. Inheritance and proxies get their own key (rebind), and a cached layout is used only by the key it was built for, so a key copied together with a config cannot point at another model's table.

Attributes:

Name Type Description
owner

model class the key belongs to

fields

ormar field names forming the key, in key order

Source code in ormar/models/primary_key.py
Python
 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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
class PrimaryKey(abc.ABC):
    """
    Primary key of a model class.

    Column names are resolved from the owner once (``layout``) and cached
    until the owner's column caches are reset. Inheritance and proxies get
    their own key (``rebind``), and a cached layout is used only by the key
    it was built for, so a key copied together with a config cannot point
    at another model's table.

    :ivar owner: model class the key belongs to
    :ivar fields: ormar field names forming the key, in key order
    """

    def __init__(self, *, owner: type["Model"], fields: tuple[str, ...]) -> None:
        """
        :param owner: model class the key belongs to
        :type owner: type[Model]
        :param fields: ormar field names forming the key, in key order
        :type fields: tuple[str, ...]
        """
        self.owner = owner
        self.fields = fields
        self.cached_layout: Optional[KeyLayout] = None
        model_fields = owner.ormar_config.model_fields
        self.relation_parts: dict[str, "ForeignKeyField"] = {
            field: cast("ForeignKeyField", model_fields[field])
            for field in fields
            if model_fields[field].is_relation
        }

    def part_value(self, field: str, value: Any) -> Any:
        """
        Turn the value a model holds for a key field into the key part: a
        related model in a relation part is replaced by the value its foreign
        key stores (e.g. the related model's pk), raw values pass through.

        :param field: key field name
        :type field: str
        :param value: value held for the field
        :type value: Any
        :return: key part
        :rtype: Any
        """
        relation_field = self.relation_parts.get(field)
        if relation_field is None or not isinstance(value, BaseModel):
            return value
        return column_value(
            model=self.owner, data={field: value}, column=relation_field.get_alias()
        )

    def part_type(self, field: str) -> Any:
        """
        :param field: key field name
        :type field: str
        :return: python type of the key part
        :rtype: Any
        """
        relation_field = self.relation_parts.get(field)
        if relation_field is not None:
            return relation_field.target_value_type()
        return self.owner.ormar_config.model_fields[field].__type__

    @property
    @abc.abstractmethod
    def is_composite(self) -> bool:
        """
        :return: whether the key spans more than one column
        :rtype: bool
        """

    def layout(self) -> KeyLayout:
        """
        :return: the key's columns, built once and cached until the owner's
            column caches are reset (not cached while a relation part still
            points at a forward reference)
        :rtype: KeyLayout
        """
        layout = self.cached_layout
        if layout is None or layout.key is not self:
            layout = self.build_layout()
            if not any(
                field.has_unresolved_forward_refs()
                for field in self.relation_parts.values()
            ):
                self.cached_layout = layout
        return layout

    def build_layout(self) -> KeyLayout:
        """
        Resolve the key's database columns: the columns of each key field in
        key order (all link columns of a foreign key), each column several
        key fields share (e.g. a ``tenant_id`` of two foreign keys) listed
        once, where it first appears.

        :return: the key's columns
        :rtype: KeyLayout
        """
        model_fields = self.owner.ormar_config.model_fields
        field_columns = [model_fields[field].column_aliases() for field in self.fields]
        column_fields: dict[str, str] = {}
        for field, columns in zip(self.fields, field_columns):
            for column in columns:
                column_fields.setdefault(column, field)
        column_aliases = tuple(column_fields)
        return KeyLayout(
            key=self,
            column_aliases=column_aliases,
            column_fields=tuple(column_fields.values()),
            simple=len(column_aliases) == len(self.fields)
            and all(len(columns) == 1 for columns in field_columns),
            bind_slots=self.slot_names(count=len(column_aliases)),
        )

    def slot_names(self, count: int) -> tuple[str, ...]:
        """
        :param count: number of key columns
        :type count: int
        :return: names of the bind parameters the key is bound to in writes
        :rtype: tuple[str, ...]
        """
        return (PK_SLOT,)

    def column_parts(self, data: Any) -> tuple[Any, ...]:
        """
        :param data: an instance of the owner, or its values by field name
            (e.g. a model dict)
        :type data: Any
        :return: the value of each key column, ``None`` for missing ones (see
            ``column_value``)
        :rtype: tuple[Any, ...]
        """
        return tuple(
            column_value(model=self.owner, data=data, column=column)
            for column in self.column_aliases()
        )

    def column_aliases(self) -> tuple[str, ...]:
        """
        :return: database column names of the key, in key order
        :rtype: tuple[str, ...]
        """
        return self.layout().column_aliases

    def columns(self) -> tuple[sqlalchemy.Column, ...]:
        """
        :return: SQLAlchemy columns of the key, in key order
        :rtype: tuple[sqlalchemy.Column, ...]
        """
        table_columns = self.owner.ormar_config.table.c
        return tuple(table_columns[alias] for alias in self.column_aliases())

    @property
    def autoincrement(self) -> bool:
        """
        :return: whether every key field is generated by the database
        :rtype: bool
        """
        model_fields = self.owner.ormar_config.model_fields
        return all(model_fields[field].autoincrement for field in self.fields)

    def bind_slots(self) -> tuple[str, ...]:
        """
        :return: names of the bind parameters the key is bound to in writes
        :rtype: tuple[str, ...]
        """
        return self.layout().bind_slots

    def where_clause(
        self, *, slots: tuple[str, ...], typed: bool = True
    ) -> sqlalchemy.ColumnElement:
        """
        Build the condition matching one row by key, each key column compared
        with a named bind parameter::

            authors.id = :ormar_pk

        :param slots: bind parameter names, one per key column
        :type slots: tuple[str, ...]
        :param typed: give each bind its column's type, so values get the
            column's bind processing (e.g. UUID)
        :type typed: bool
        :return: condition over the key columns
        :rtype: sqlalchemy.ColumnElement
        """
        comparisons = [
            column
            == (
                sqlalchemy.bindparam(key=slot, type_=column.type)
                if typed
                else sqlalchemy.bindparam(key=slot)
            )
            for column, slot in zip(self.columns(), slots)
        ]
        return sqlalchemy.and_(*comparisons)

    def row_value(self) -> sqlalchemy.ColumnElement:
        """
        :return: the key column, or the key columns as a tuple for a composite
            key, to compare whole keys: ``authors.id`` / ``(orders.a, orders.b)``
        :rtype: sqlalchemy.ColumnElement
        """
        columns = self.columns()
        return columns[0] if len(columns) == 1 else sqlalchemy.tuple_(*columns)

    def in_clause(self, *, slot: str) -> sqlalchemy.ColumnElement:
        """
        Build the condition matching the rows of a list of keys bound to one
        expanding parameter, one value per row (a tuple for a composite key)::

            authors.id IN (:ormar_pks)  # rendered as IN (?, ?, ...) per call

        :param slot: bind parameter name
        :type slot: str
        :return: condition over the key columns
        :rtype: sqlalchemy.ColumnElement
        """
        target = self.row_value()
        return target.in_(
            sqlalchemy.bindparam(key=slot, expanding=True, type_=target.type)
        )

    def expand_pk_kwarg(self, kwargs: dict[str, Any]) -> dict[str, Any]:
        """
        Replace a ``pk`` keyword with the key fields it stands for::

            {"pk": 4, "title": "a"} -> {"id": 4, "title": "a"}

        :param kwargs: keyword arguments, possibly holding ``pk``
        :type kwargs: dict[str, Any]
        :return: new keyword arguments without ``pk``
        :rtype: dict[str, Any]
        """
        if "pk" not in kwargs:
            return dict(kwargs)
        expanded = {name: value for name, value in kwargs.items() if name != "pk"}
        expanded.update(self.to_dict(value=kwargs["pk"]))
        return expanded

    def lookup(self, kwargs: dict[str, Any]) -> Optional[dict[str, Any]]:
        """
        :param kwargs: keyword arguments by field name
        :type kwargs: dict[str, Any]
        :return: the key fields and their values, ``None`` when any key field
            is missing or ``None``
        :rtype: Optional[dict[str, Any]]
        """
        if any(kwargs.get(field) is None for field in self.fields):
            return None
        return {field: kwargs[field] for field in self.fields}

    def rebind(self, *, owner: type["Model"]) -> "PrimaryKey":
        """
        :param owner: model class the new key belongs to
        :type owner: type[Model]
        :return: the same key for another model class (inheritance, proxies)
        :rtype: PrimaryKey
        """
        return type(self)(owner=owner, fields=self.fields)

    @abc.abstractmethod
    def python_type(self) -> Any:
        """
        :return: python type of the key value
        :rtype: Any
        """

    @abc.abstractmethod
    def value(self, instance: "NewBaseModel") -> Any:
        """
        :param instance: model instance
        :type instance: NewBaseModel
        :return: key value of the instance
        :rtype: Any
        """

    @abc.abstractmethod
    def to_dict(self, value: Any) -> dict[str, Any]:
        """
        :param value: key value
        :type value: Any
        :return: key value split into its fields, by field name
        :rtype: dict[str, Any]
        """

    @abc.abstractmethod
    def getter(self, keys: tuple[str, ...]) -> Callable[[Mapping[str, Any]], Any]:
        """
        :param keys: names under which the key parts are stored in a mapping
            (field names in a model dict, column names in a row)
        :type keys: tuple[str, ...]
        :return: callable reading the key value out of such a mapping
        :rtype: Callable[[Mapping[str, Any]], Any]
        """

    def item_reader(self) -> Callable[[Mapping[str, Any]], Any]:
        """
        :return: callable reading the key value out of a model dict (values
            by field name, a foreign key stored in several columns holding
            the tuple of its columns)
        :rtype: Callable[[Mapping[str, Any]], Any]
        """
        if self.layout().simple:
            return self.getter(keys=self.fields)
        return self.value_from

    @abc.abstractmethod
    def value_from(self, data: Mapping[str, Any]) -> Any:
        """
        :param data: values by field name (e.g. a model dict)
        :type data: Mapping[str, Any]
        :return: key value held in the mapping, ``None`` when not set
        :rtype: Any
        """

    @abc.abstractmethod
    def flat_parts(self, value: Any) -> tuple[Any, ...]:
        """
        :param value: key value
        :type value: Any
        :return: the raw value of each key column, in key order
        :rtype: tuple[Any, ...]
        """

    @abc.abstractmethod
    def bind_params(self, value: Any) -> dict[str, Any]:
        """
        :param value: key value
        :type value: Any
        :return: parameters binding the value to ``bind_slots()``
        :rtype: dict[str, Any]
        """

autoincrement property

Returns:

Type Description
bool

whether every key field is generated by the database

is_composite abstractmethod property

Returns:

Type Description
bool

whether the key spans more than one column

__init__(*, owner, fields)

Parameters:

Name Type Description Default
owner type[Model]

model class the key belongs to

required
fields tuple[str, ...]

ormar field names forming the key, in key order

required
Source code in ormar/models/primary_key.py
Python
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
def __init__(self, *, owner: type["Model"], fields: tuple[str, ...]) -> None:
    """
    :param owner: model class the key belongs to
    :type owner: type[Model]
    :param fields: ormar field names forming the key, in key order
    :type fields: tuple[str, ...]
    """
    self.owner = owner
    self.fields = fields
    self.cached_layout: Optional[KeyLayout] = None
    model_fields = owner.ormar_config.model_fields
    self.relation_parts: dict[str, "ForeignKeyField"] = {
        field: cast("ForeignKeyField", model_fields[field])
        for field in fields
        if model_fields[field].is_relation
    }

bind_params(value) abstractmethod

Parameters:

Name Type Description Default
value Any

key value

required

Returns:

Type Description
dict[str, Any]

parameters binding the value to bind_slots()

Source code in ormar/models/primary_key.py
Python
389
390
391
392
393
394
395
396
@abc.abstractmethod
def bind_params(self, value: Any) -> dict[str, Any]:
    """
    :param value: key value
    :type value: Any
    :return: parameters binding the value to ``bind_slots()``
    :rtype: dict[str, Any]
    """

bind_slots()

Returns:

Type Description
tuple[str, ...]

names of the bind parameters the key is bound to in writes

Source code in ormar/models/primary_key.py
Python
226
227
228
229
230
231
def bind_slots(self) -> tuple[str, ...]:
    """
    :return: names of the bind parameters the key is bound to in writes
    :rtype: tuple[str, ...]
    """
    return self.layout().bind_slots

build_layout()

Resolve the key's database columns: the columns of each key field in key order (all link columns of a foreign key), each column several key fields share (e.g. a tenant_id of two foreign keys) listed once, where it first appears.

Returns:

Type Description
KeyLayout

the key's columns

Source code in ormar/models/primary_key.py
Python
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
def build_layout(self) -> KeyLayout:
    """
    Resolve the key's database columns: the columns of each key field in
    key order (all link columns of a foreign key), each column several
    key fields share (e.g. a ``tenant_id`` of two foreign keys) listed
    once, where it first appears.

    :return: the key's columns
    :rtype: KeyLayout
    """
    model_fields = self.owner.ormar_config.model_fields
    field_columns = [model_fields[field].column_aliases() for field in self.fields]
    column_fields: dict[str, str] = {}
    for field, columns in zip(self.fields, field_columns):
        for column in columns:
            column_fields.setdefault(column, field)
    column_aliases = tuple(column_fields)
    return KeyLayout(
        key=self,
        column_aliases=column_aliases,
        column_fields=tuple(column_fields.values()),
        simple=len(column_aliases) == len(self.fields)
        and all(len(columns) == 1 for columns in field_columns),
        bind_slots=self.slot_names(count=len(column_aliases)),
    )

column_aliases()

Returns:

Type Description
tuple[str, ...]

database column names of the key, in key order

Source code in ormar/models/primary_key.py
Python
202
203
204
205
206
207
def column_aliases(self) -> tuple[str, ...]:
    """
    :return: database column names of the key, in key order
    :rtype: tuple[str, ...]
    """
    return self.layout().column_aliases

column_parts(data)

Parameters:

Name Type Description Default
data Any

an instance of the owner, or its values by field name (e.g. a model dict)

required

Returns:

Type Description
tuple[Any, ...]

the value of each key column, None for missing ones (see column_value)

Source code in ormar/models/primary_key.py
Python
188
189
190
191
192
193
194
195
196
197
198
199
200
def column_parts(self, data: Any) -> tuple[Any, ...]:
    """
    :param data: an instance of the owner, or its values by field name
        (e.g. a model dict)
    :type data: Any
    :return: the value of each key column, ``None`` for missing ones (see
        ``column_value``)
    :rtype: tuple[Any, ...]
    """
    return tuple(
        column_value(model=self.owner, data=data, column=column)
        for column in self.column_aliases()
    )

columns()

Returns:

Type Description
tuple[sqlalchemy.Column, ...]

SQLAlchemy columns of the key, in key order

Source code in ormar/models/primary_key.py
Python
209
210
211
212
213
214
215
def columns(self) -> tuple[sqlalchemy.Column, ...]:
    """
    :return: SQLAlchemy columns of the key, in key order
    :rtype: tuple[sqlalchemy.Column, ...]
    """
    table_columns = self.owner.ormar_config.table.c
    return tuple(table_columns[alias] for alias in self.column_aliases())

expand_pk_kwarg(kwargs)

Replace a pk keyword with the key fields it stands for::

Text Only
1
{"pk": 4, "title": "a"} -> {"id": 4, "title": "a"}

Parameters:

Name Type Description Default
kwargs dict[str, Any]

keyword arguments, possibly holding pk

required

Returns:

Type Description
dict[str, Any]

new keyword arguments without pk

Source code in ormar/models/primary_key.py
Python
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
def expand_pk_kwarg(self, kwargs: dict[str, Any]) -> dict[str, Any]:
    """
    Replace a ``pk`` keyword with the key fields it stands for::

        {"pk": 4, "title": "a"} -> {"id": 4, "title": "a"}

    :param kwargs: keyword arguments, possibly holding ``pk``
    :type kwargs: dict[str, Any]
    :return: new keyword arguments without ``pk``
    :rtype: dict[str, Any]
    """
    if "pk" not in kwargs:
        return dict(kwargs)
    expanded = {name: value for name, value in kwargs.items() if name != "pk"}
    expanded.update(self.to_dict(value=kwargs["pk"]))
    return expanded

flat_parts(value) abstractmethod

Parameters:

Name Type Description Default
value Any

key value

required

Returns:

Type Description
tuple[Any, ...]

the raw value of each key column, in key order

Source code in ormar/models/primary_key.py
Python
380
381
382
383
384
385
386
387
@abc.abstractmethod
def flat_parts(self, value: Any) -> tuple[Any, ...]:
    """
    :param value: key value
    :type value: Any
    :return: the raw value of each key column, in key order
    :rtype: tuple[Any, ...]
    """

getter(keys) abstractmethod

Parameters:

Name Type Description Default
keys tuple[str, ...]

names under which the key parts are stored in a mapping (field names in a model dict, column names in a row)

required

Returns:

Type Description
Callable[[Mapping[str, Any]], Any]

callable reading the key value out of such a mapping

Source code in ormar/models/primary_key.py
Python
350
351
352
353
354
355
356
357
358
@abc.abstractmethod
def getter(self, keys: tuple[str, ...]) -> Callable[[Mapping[str, Any]], Any]:
    """
    :param keys: names under which the key parts are stored in a mapping
        (field names in a model dict, column names in a row)
    :type keys: tuple[str, ...]
    :return: callable reading the key value out of such a mapping
    :rtype: Callable[[Mapping[str, Any]], Any]
    """

in_clause(*, slot)

Build the condition matching the rows of a list of keys bound to one expanding parameter, one value per row (a tuple for a composite key)::

Text Only
1
authors.id IN (:ormar_pks)  # rendered as IN (?, ?, ...) per call

Parameters:

Name Type Description Default
slot str

bind parameter name

required

Returns:

Type Description
sqlalchemy.ColumnElement

condition over the key columns

Source code in ormar/models/primary_key.py
Python
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
def in_clause(self, *, slot: str) -> sqlalchemy.ColumnElement:
    """
    Build the condition matching the rows of a list of keys bound to one
    expanding parameter, one value per row (a tuple for a composite key)::

        authors.id IN (:ormar_pks)  # rendered as IN (?, ?, ...) per call

    :param slot: bind parameter name
    :type slot: str
    :return: condition over the key columns
    :rtype: sqlalchemy.ColumnElement
    """
    target = self.row_value()
    return target.in_(
        sqlalchemy.bindparam(key=slot, expanding=True, type_=target.type)
    )

item_reader()

Returns:

Type Description
Callable[[Mapping[str, Any]], Any]

callable reading the key value out of a model dict (values by field name, a foreign key stored in several columns holding the tuple of its columns)

Source code in ormar/models/primary_key.py
Python
360
361
362
363
364
365
366
367
368
369
def item_reader(self) -> Callable[[Mapping[str, Any]], Any]:
    """
    :return: callable reading the key value out of a model dict (values
        by field name, a foreign key stored in several columns holding
        the tuple of its columns)
    :rtype: Callable[[Mapping[str, Any]], Any]
    """
    if self.layout().simple:
        return self.getter(keys=self.fields)
    return self.value_from

layout()

Returns:

Type Description
KeyLayout

the key's columns, built once and cached until the owner's column caches are reset (not cached while a relation part still points at a forward reference)

Source code in ormar/models/primary_key.py
Python
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
def layout(self) -> KeyLayout:
    """
    :return: the key's columns, built once and cached until the owner's
        column caches are reset (not cached while a relation part still
        points at a forward reference)
    :rtype: KeyLayout
    """
    layout = self.cached_layout
    if layout is None or layout.key is not self:
        layout = self.build_layout()
        if not any(
            field.has_unresolved_forward_refs()
            for field in self.relation_parts.values()
        ):
            self.cached_layout = layout
    return layout

lookup(kwargs)

Parameters:

Name Type Description Default
kwargs dict[str, Any]

keyword arguments by field name

required

Returns:

Type Description
Optional[dict[str, Any]]

the key fields and their values, None when any key field is missing or None

Source code in ormar/models/primary_key.py
Python
304
305
306
307
308
309
310
311
312
313
314
def lookup(self, kwargs: dict[str, Any]) -> Optional[dict[str, Any]]:
    """
    :param kwargs: keyword arguments by field name
    :type kwargs: dict[str, Any]
    :return: the key fields and their values, ``None`` when any key field
        is missing or ``None``
    :rtype: Optional[dict[str, Any]]
    """
    if any(kwargs.get(field) is None for field in self.fields):
        return None
    return {field: kwargs[field] for field in self.fields}

part_type(field)

Parameters:

Name Type Description Default
field str

key field name

required

Returns:

Type Description
Any

python type of the key part

Source code in ormar/models/primary_key.py
Python
116
117
118
119
120
121
122
123
124
125
126
def part_type(self, field: str) -> Any:
    """
    :param field: key field name
    :type field: str
    :return: python type of the key part
    :rtype: Any
    """
    relation_field = self.relation_parts.get(field)
    if relation_field is not None:
        return relation_field.target_value_type()
    return self.owner.ormar_config.model_fields[field].__type__

part_value(field, value)

Turn the value a model holds for a key field into the key part: a related model in a relation part is replaced by the value its foreign key stores (e.g. the related model's pk), raw values pass through.

Parameters:

Name Type Description Default
field str

key field name

required
value Any

value held for the field

required

Returns:

Type Description
Any

key part

Source code in ormar/models/primary_key.py
Python
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
def part_value(self, field: str, value: Any) -> Any:
    """
    Turn the value a model holds for a key field into the key part: a
    related model in a relation part is replaced by the value its foreign
    key stores (e.g. the related model's pk), raw values pass through.

    :param field: key field name
    :type field: str
    :param value: value held for the field
    :type value: Any
    :return: key part
    :rtype: Any
    """
    relation_field = self.relation_parts.get(field)
    if relation_field is None or not isinstance(value, BaseModel):
        return value
    return column_value(
        model=self.owner, data={field: value}, column=relation_field.get_alias()
    )

python_type() abstractmethod

Returns:

Type Description
Any

python type of the key value

Source code in ormar/models/primary_key.py
Python
325
326
327
328
329
330
@abc.abstractmethod
def python_type(self) -> Any:
    """
    :return: python type of the key value
    :rtype: Any
    """

rebind(*, owner)

Parameters:

Name Type Description Default
owner type[Model]

model class the new key belongs to

required

Returns:

Type Description
PrimaryKey

the same key for another model class (inheritance, proxies)

Source code in ormar/models/primary_key.py
Python
316
317
318
319
320
321
322
323
def rebind(self, *, owner: type["Model"]) -> "PrimaryKey":
    """
    :param owner: model class the new key belongs to
    :type owner: type[Model]
    :return: the same key for another model class (inheritance, proxies)
    :rtype: PrimaryKey
    """
    return type(self)(owner=owner, fields=self.fields)

row_value()

Returns:

Type Description
sqlalchemy.ColumnElement

the key column, or the key columns as a tuple for a composite key, to compare whole keys: authors.id / (orders.a, orders.b)

Source code in ormar/models/primary_key.py
Python
261
262
263
264
265
266
267
268
def row_value(self) -> sqlalchemy.ColumnElement:
    """
    :return: the key column, or the key columns as a tuple for a composite
        key, to compare whole keys: ``authors.id`` / ``(orders.a, orders.b)``
    :rtype: sqlalchemy.ColumnElement
    """
    columns = self.columns()
    return columns[0] if len(columns) == 1 else sqlalchemy.tuple_(*columns)

slot_names(count)

Parameters:

Name Type Description Default
count int

number of key columns

required

Returns:

Type Description
tuple[str, ...]

names of the bind parameters the key is bound to in writes

Source code in ormar/models/primary_key.py
Python
179
180
181
182
183
184
185
186
def slot_names(self, count: int) -> tuple[str, ...]:
    """
    :param count: number of key columns
    :type count: int
    :return: names of the bind parameters the key is bound to in writes
    :rtype: tuple[str, ...]
    """
    return (PK_SLOT,)

to_dict(value) abstractmethod

Parameters:

Name Type Description Default
value Any

key value

required

Returns:

Type Description
dict[str, Any]

key value split into its fields, by field name

Source code in ormar/models/primary_key.py
Python
341
342
343
344
345
346
347
348
@abc.abstractmethod
def to_dict(self, value: Any) -> dict[str, Any]:
    """
    :param value: key value
    :type value: Any
    :return: key value split into its fields, by field name
    :rtype: dict[str, Any]
    """

value(instance) abstractmethod

Parameters:

Name Type Description Default
instance NewBaseModel

model instance

required

Returns:

Type Description
Any

key value of the instance

Source code in ormar/models/primary_key.py
Python
332
333
334
335
336
337
338
339
@abc.abstractmethod
def value(self, instance: "NewBaseModel") -> Any:
    """
    :param instance: model instance
    :type instance: NewBaseModel
    :return: key value of the instance
    :rtype: Any
    """

value_from(data) abstractmethod

Parameters:

Name Type Description Default
data Mapping[str, Any]

values by field name (e.g. a model dict)

required

Returns:

Type Description
Any

key value held in the mapping, None when not set

Source code in ormar/models/primary_key.py
Python
371
372
373
374
375
376
377
378
@abc.abstractmethod
def value_from(self, data: Mapping[str, Any]) -> Any:
    """
    :param data: values by field name (e.g. a model dict)
    :type data: Mapping[str, Any]
    :return: key value held in the mapping, ``None`` when not set
    :rtype: Any
    """

where_clause(*, slots, typed=True)

Build the condition matching one row by key, each key column compared with a named bind parameter::

Text Only
1
authors.id = :ormar_pk

Parameters:

Name Type Description Default
slots tuple[str, ...]

bind parameter names, one per key column

required
typed bool

give each bind its column's type, so values get the column's bind processing (e.g. UUID)

True

Returns:

Type Description
sqlalchemy.ColumnElement

condition over the key columns

Source code in ormar/models/primary_key.py
Python
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
def where_clause(
    self, *, slots: tuple[str, ...], typed: bool = True
) -> sqlalchemy.ColumnElement:
    """
    Build the condition matching one row by key, each key column compared
    with a named bind parameter::

        authors.id = :ormar_pk

    :param slots: bind parameter names, one per key column
    :type slots: tuple[str, ...]
    :param typed: give each bind its column's type, so values get the
        column's bind processing (e.g. UUID)
    :type typed: bool
    :return: condition over the key columns
    :rtype: sqlalchemy.ColumnElement
    """
    comparisons = [
        column
        == (
            sqlalchemy.bindparam(key=slot, type_=column.type)
            if typed
            else sqlalchemy.bindparam(key=slot)
        )
        for column, slot in zip(self.columns(), slots)
    ]
    return sqlalchemy.and_(*comparisons)

SingleColumnKey

Bases: PrimaryKey

Primary key of one column, whose value is a plain scalar.

Attributes:

Name Type Description
field

name of the key field

Source code in ormar/models/primary_key.py
Python
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
class SingleColumnKey(PrimaryKey):
    """
    Primary key of one column, whose value is a plain scalar.

    :ivar field: name of the key field
    """

    def __init__(self, *, owner: type["Model"], fields: tuple[str, ...]) -> None:
        """
        :param owner: model class the key belongs to
        :type owner: type[Model]
        :param fields: the one key field name
        :type fields: tuple[str, ...]
        """
        super().__init__(owner=owner, fields=fields)
        self.field = fields[0]

    @property
    def is_composite(self) -> bool:
        """
        :return: always ``False``
        :rtype: bool
        """
        return False

    def python_type(self) -> Any:
        """
        :return: python type of the key field
        :rtype: Any
        """
        return self.part_type(field=self.field)

    def value(self, instance: "NewBaseModel") -> Any:
        """
        :param instance: model instance
        :type instance: NewBaseModel
        :return: value of the key field, ``None`` if not set
        :rtype: Any
        """
        value = instance.__dict__.get(self.field)
        if self.relation_parts:
            return self.part_value(field=self.field, value=value)
        return value

    def to_dict(self, value: Any) -> dict[str, Any]:
        """
        :param value: key value
        :type value: Any
        :return: ``{key field: value}``
        :rtype: dict[str, Any]
        """
        return {self.fields[0]: value}

    def getter(self, keys: tuple[str, ...]) -> Callable[[Mapping[str, Any]], Any]:
        """
        :param keys: one name under which the key is stored
        :type keys: tuple[str, ...]
        :return: ``operator.itemgetter`` of that name
        :rtype: Callable[[Mapping[str, Any]], Any]
        """
        return operator.itemgetter(keys[0])

    def value_from(self, data: Mapping[str, Any]) -> Any:
        """
        :param data: values by field name (e.g. a model dict)
        :type data: Mapping[str, Any]
        :return: value of the key field, ``None`` when not set
        :rtype: Any
        """
        value = data.get(self.field)
        if self.relation_parts:
            return self.part_value(field=self.field, value=value)
        return value

    def flat_parts(self, value: Any) -> tuple[Any, ...]:
        """
        :param value: key value
        :type value: Any
        :return: ``(value,)``, a related model replaced by its raw value
        :rtype: tuple[Any, ...]
        """
        return (self.part_value(field=self.field, value=value),)

    def bind_params(self, value: Any) -> dict[str, Any]:
        """
        :param value: key value
        :type value: Any
        :return: ``{"ormar_pk": value}``
        :rtype: dict[str, Any]
        """
        return {PK_SLOT: value}

is_composite property

Returns:

Type Description
bool

always False

__init__(*, owner, fields)

Parameters:

Name Type Description Default
owner type[Model]

model class the key belongs to

required
fields tuple[str, ...]

the one key field name

required
Source code in ormar/models/primary_key.py
Python
406
407
408
409
410
411
412
413
414
def __init__(self, *, owner: type["Model"], fields: tuple[str, ...]) -> None:
    """
    :param owner: model class the key belongs to
    :type owner: type[Model]
    :param fields: the one key field name
    :type fields: tuple[str, ...]
    """
    super().__init__(owner=owner, fields=fields)
    self.field = fields[0]

bind_params(value)

Parameters:

Name Type Description Default
value Any

key value

required

Returns:

Type Description
dict[str, Any]

{"ormar_pk": value}

Source code in ormar/models/primary_key.py
Python
482
483
484
485
486
487
488
489
def bind_params(self, value: Any) -> dict[str, Any]:
    """
    :param value: key value
    :type value: Any
    :return: ``{"ormar_pk": value}``
    :rtype: dict[str, Any]
    """
    return {PK_SLOT: value}

flat_parts(value)

Parameters:

Name Type Description Default
value Any

key value

required

Returns:

Type Description
tuple[Any, ...]

(value,), a related model replaced by its raw value

Source code in ormar/models/primary_key.py
Python
473
474
475
476
477
478
479
480
def flat_parts(self, value: Any) -> tuple[Any, ...]:
    """
    :param value: key value
    :type value: Any
    :return: ``(value,)``, a related model replaced by its raw value
    :rtype: tuple[Any, ...]
    """
    return (self.part_value(field=self.field, value=value),)

getter(keys)

Parameters:

Name Type Description Default
keys tuple[str, ...]

one name under which the key is stored

required

Returns:

Type Description
Callable[[Mapping[str, Any]], Any]

operator.itemgetter of that name

Source code in ormar/models/primary_key.py
Python
452
453
454
455
456
457
458
459
def getter(self, keys: tuple[str, ...]) -> Callable[[Mapping[str, Any]], Any]:
    """
    :param keys: one name under which the key is stored
    :type keys: tuple[str, ...]
    :return: ``operator.itemgetter`` of that name
    :rtype: Callable[[Mapping[str, Any]], Any]
    """
    return operator.itemgetter(keys[0])

python_type()

Returns:

Type Description
Any

python type of the key field

Source code in ormar/models/primary_key.py
Python
424
425
426
427
428
429
def python_type(self) -> Any:
    """
    :return: python type of the key field
    :rtype: Any
    """
    return self.part_type(field=self.field)

to_dict(value)

Parameters:

Name Type Description Default
value Any

key value

required

Returns:

Type Description
dict[str, Any]

{key field: value}

Source code in ormar/models/primary_key.py
Python
443
444
445
446
447
448
449
450
def to_dict(self, value: Any) -> dict[str, Any]:
    """
    :param value: key value
    :type value: Any
    :return: ``{key field: value}``
    :rtype: dict[str, Any]
    """
    return {self.fields[0]: value}

value(instance)

Parameters:

Name Type Description Default
instance NewBaseModel

model instance

required

Returns:

Type Description
Any

value of the key field, None if not set

Source code in ormar/models/primary_key.py
Python
431
432
433
434
435
436
437
438
439
440
441
def value(self, instance: "NewBaseModel") -> Any:
    """
    :param instance: model instance
    :type instance: NewBaseModel
    :return: value of the key field, ``None`` if not set
    :rtype: Any
    """
    value = instance.__dict__.get(self.field)
    if self.relation_parts:
        return self.part_value(field=self.field, value=value)
    return value

value_from(data)

Parameters:

Name Type Description Default
data Mapping[str, Any]

values by field name (e.g. a model dict)

required

Returns:

Type Description
Any

value of the key field, None when not set

Source code in ormar/models/primary_key.py
Python
461
462
463
464
465
466
467
468
469
470
471
def value_from(self, data: Mapping[str, Any]) -> Any:
    """
    :param data: values by field name (e.g. a model dict)
    :type data: Mapping[str, Any]
    :return: value of the key field, ``None`` when not set
    :rtype: Any
    """
    value = data.get(self.field)
    if self.relation_parts:
        return self.part_value(field=self.field, value=value)
    return value

build_primary_key(*, owner, fields)

Create the primary key of a model from the fields marked as primary key.

Parameters:

Name Type Description Default
owner type[Model]

model class the key belongs to

required
fields tuple[str, ...]

ormar field names marked as primary key, in declaration order

required

Returns:

Type Description
PrimaryKey

primary key of the model

Source code in ormar/models/primary_key.py
Python
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
def build_primary_key(*, owner: type["Model"], fields: tuple[str, ...]) -> PrimaryKey:
    """
    Create the primary key of a model from the fields marked as primary key.

    :param owner: model class the key belongs to
    :type owner: type[Model]
    :param fields: ormar field names marked as primary key, in declaration order
    :type fields: tuple[str, ...]
    :return: primary key of the model
    :rtype: PrimaryKey
    """
    if (
        len(fields) > 1
        or len(owner.ormar_config.model_fields[fields[0]].column_aliases()) > 1
    ):
        return CompositeKey(owner=owner, fields=fields)
    return SingleColumnKey(owner=owner, fields=fields)

not_scalar(parts)

Parameters:

Name Type Description Default
parts tuple[Any, ...]

values of the key columns

required

Returns:

Type Description
bool

whether any column got a tuple, list, dict or model instead of a single value

Source code in ormar/models/primary_key.py
Python
51
52
53
54
55
56
57
58
59
60
61
62
def not_scalar(parts: tuple[Any, ...]) -> bool:
    """
    :param parts: values of the key columns
    :type parts: tuple[Any, ...]
    :return: whether any column got a tuple, list, dict or model instead of
        a single value
    :rtype: bool
    """
    for part in parts:
        if isinstance(part, NOT_SCALAR):
            return True
    return False