Skip to content

values_columns

Maps prefixed columns of a raw query to the relation string keys returned by values() and values_list().

ReturnedColumn dataclass

A field of the query columns resolved for values().

Attributes:

Name Type Description
name str

name of the field

relation Optional[ForeignKeyField]

the field, for a foreign key stored in several columns

part str

target column the column stores, for such a foreign key (empty otherwise)

Source code in ormar/queryset/values_columns.py
Python
33
34
35
36
37
38
39
40
41
42
43
44
45
46
@dataclass(frozen=True)
class ReturnedColumn:
    """
    A field of the query columns resolved for ``values()``.

    :ivar name: name of the field
    :ivar relation: the field, for a foreign key stored in several columns
    :ivar part: target column the column stores, for such a foreign key
        (empty otherwise)
    """

    name: str
    relation: Optional["ForeignKeyField"] = None
    part: str = ""

ValuesColumns dataclass

Columns of a raw query returned by values() / values_list().

Attributes:

Name Type Description
names tuple[tuple[str, str], ...]

(query column label, returned name) pairs in query order; the columns of a foreign key stored in several columns share one name, a column several fields share is listed once per field

key_parts dict[tuple[str, str], ReturnedColumn]

resolved column by (label, name), for the columns of foreign keys stored in several columns

Source code in ormar/queryset/values_columns.py
Python
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@dataclass(frozen=True)
class ValuesColumns:
    """
    Columns of a raw query returned by ``values()`` / ``values_list()``.

    :ivar names: ``(query column label, returned name)`` pairs in query
        order; the columns of a foreign key stored in several columns share
        one name, a column several fields share is listed once per field
    :ivar key_parts: resolved column by ``(label, name)``, for the columns of
        foreign keys stored in several columns
    """

    names: tuple[tuple[str, str], ...]
    key_parts: dict[tuple[str, str], "ReturnedColumn"]

allowed_columns(model_cls, excludable, alias, is_excluded)

Returns the columns of a joined table that should be returned to the user, without the primary key columns added only to construct models.

Parameters:

Name Type Description Default
model_cls type[Model]

model of the joined table

required
excludable ExcludableItems

structure of fields to include and exclude

required
alias str

alias of the joined table

required
is_excluded bool

flag if the relation is excluded on its parent model

required

Returns:

Type Description
set[str]

set of column names

Source code in ormar/queryset/values_columns.py
Python
 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
def allowed_columns(
    model_cls: type["Model"],
    excludable: "ExcludableItems",
    alias: str,
    is_excluded: bool,
) -> set[str]:
    """
    Returns the columns of a joined table that should be returned to the user,
    without the primary key columns added only to construct models.

    :param model_cls: model of the joined table
    :type model_cls: type["Model"]
    :param excludable: structure of fields to include and exclude
    :type excludable: ExcludableItems
    :param alias: alias of the joined table
    :type alias: str
    :param is_excluded: flag if the relation is excluded on its parent model
    :type is_excluded: bool
    :return: set of column names
    :rtype: set[str]
    """
    if is_excluded:
        return set()
    return set(
        model_cls.own_table_columns(
            model=model_cls, excludable=excludable, alias=alias, add_pk_columns=False
        )
    )

extract_grouped_values(rows, columns, as_dict)

Extract values of a query returning foreign keys stored in several columns, combining their columns into one value (see extract_values).

Parameters:

Name Type Description Default
rows list[Any]

database rows

required
columns ValuesColumns

returned columns of the query

required
as_dict bool

return dictionaries instead of tuples

required

Returns:

Type Description
list[Any]

extracted values

Source code in ormar/queryset/values_columns.py
Python
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
def extract_grouped_values(
    rows: list[Any], columns: ValuesColumns, as_dict: bool
) -> list[Any]:
    """
    Extract values of a query returning foreign keys stored in several
    columns, combining their columns into one value (see ``extract_values``).

    :param rows: database rows
    :type rows: list[Any]
    :param columns: returned columns of the query
    :type columns: ValuesColumns
    :param as_dict: return dictionaries instead of tuples
    :type as_dict: bool
    :return: extracted values
    :rtype: list[Any]
    """
    groups: dict[str, list[str]] = dict()
    for label, name in columns.names:
        groups.setdefault(name, []).append(label)
    result = []
    for row in rows:
        values = [
            group_value(
                row=row, name=name, labels=labels, columns=columns, as_dict=as_dict
            )
            for name, labels in groups.items()
        ]
        result.append(dict(zip(groups, values)) if as_dict else tuple(values))
    return result

extract_values(rows, columns, as_dict)

Extracts the mapped columns of each row, in the order of the query columns, as a dictionary keyed by relation string or as a tuple of values.

Sample: with names (("t1a2b3c_name", "posts__user__name"),) a row {"id": 1, "t1a2b3c_name": "a"} becomes {"posts__user__name": "a"} or ("a",)

A foreign key stored in several columns is one value: a dict of its target fields ({"tenant_id": 1, "number": 7}) or, in tuples, a tuple ((1, 7)), None when any of its columns is null.

Rows of a query whose labels are already the returned names, with no column skipped, are copied as a whole.

Parameters:

Name Type Description Default
rows list[Any]

database rows

required
columns ValuesColumns

returned columns of the query

required
as_dict bool

return dictionaries instead of tuples

required

Returns:

Type Description
list[Any]

extracted values

Source code in ormar/queryset/values_columns.py
Python
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
def extract_values(rows: list[Any], columns: ValuesColumns, as_dict: bool) -> list[Any]:
    """
    Extracts the mapped columns of each row, in the order of the query columns,
    as a dictionary keyed by relation string or as a tuple of values.

    Sample: with names (("t1a2b3c_name", "posts__user__name"),) a row
    {"id": 1, "t1a2b3c_name": "a"} becomes {"posts__user__name": "a"} or ("a",)

    A foreign key stored in several columns is one value: a dict of its
    target fields (``{"tenant_id": 1, "number": 7}``) or, in tuples, a tuple
    (``(1, 7)``), ``None`` when any of its columns is null.

    Rows of a query whose labels are already the returned names, with no
    column skipped, are copied as a whole.

    :param rows: database rows
    :type rows: list[Any]
    :param columns: returned columns of the query
    :type columns: ValuesColumns
    :param as_dict: return dictionaries instead of tuples
    :type as_dict: bool
    :return: extracted values
    :rtype: list[Any]
    """
    if columns.key_parts:
        return extract_grouped_values(rows=rows, columns=columns, as_dict=as_dict)
    labels = [label for label, _ in columns.names]
    names = [name for _, name in columns.names]
    if as_dict and labels == names == list(rows[0].keys()):
        return [dict(row) for row in rows]
    if len(labels) > 1:
        values = list(map(itemgetter(*labels), rows))
    else:  # itemgetter of a single label returns a bare value, not a tuple
        values = [tuple(row[label] for label in labels) for row in rows]
    if not as_dict:
        return values
    return [dict(zip(names, row_values)) for row_values in values]

group_value(row, name, labels, columns, as_dict)

Parameters:

Name Type Description Default
row Any

database row

required
name str

returned name

required
labels list[str]

query column labels of the returned name

required
columns ValuesColumns

returned columns of the query

required
as_dict bool

shape a foreign key stored in several columns as a dict

required

Returns:

Type Description
Any

the value of the returned name

Source code in ormar/queryset/values_columns.py
Python
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
def group_value(
    row: Any, name: str, labels: list[str], columns: ValuesColumns, as_dict: bool
) -> Any:
    """
    :param row: database row
    :type row: Any
    :param name: returned name
    :type name: str
    :param labels: query column labels of the returned name
    :type labels: list[str]
    :param columns: returned columns of the query
    :type columns: ValuesColumns
    :param as_dict: shape a foreign key stored in several columns as a dict
    :type as_dict: bool
    :return: the value of the returned name
    :rtype: Any
    """
    first = columns.key_parts.get((labels[0], name))
    if first is None:
        return row[labels[0]]
    values = {columns.key_parts[(label, name)].part: row[label] for label in labels}
    if None in values.values():
        return None
    relation = cast("ForeignKeyField", first.relation)
    if as_dict:
        return relation.flat_from_columns(values=values)
    return tuple(values[column] for column in relation.link.target_columns())

joined_table_columns(model_cls, select_related, excludable, exclude_through)

Maps the alias of each joined table to the relation string used to label its columns and the set of its columns that should be returned.

Through tables of many to many relations are labelled with the through model name following the parent relation string. Relations excluded on their parent model keep their alias with no columns, so their columns are not mistaken for columns of the main model.

Parameters:

Name Type Description Default
model_cls type[Model]

main model of the query

required
select_related list[str]

list of related relation strings joined in the query

required
excludable ExcludableItems

structure of fields to include and exclude

required
exclude_through bool

flag if through models should be excluded

required

Returns:

Type Description
dict[str, tuple[str, set[str]]]

dictionary of table alias to label and allowed columns

Source code in ormar/queryset/values_columns.py
Python
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
def joined_table_columns(
    model_cls: type["Model"],
    select_related: list[str],
    excludable: "ExcludableItems",
    exclude_through: bool,
) -> dict[str, tuple[str, type["Model"], set[str]]]:
    """
    Maps the alias of each joined table to the relation string used to label
    its columns and the set of its columns that should be returned.

    Through tables of many to many relations are labelled with the through
    model name following the parent relation string.
    Relations excluded on their parent model keep their alias with no columns,
    so their columns are not mistaken for columns of the main model.

    :param model_cls: main model of the query
    :type model_cls: type["Model"]
    :param select_related: list of related relation strings joined in the query
    :type select_related: list[str]
    :param excludable: structure of fields to include and exclude
    :type excludable: ExcludableItems
    :param exclude_through: flag if through models should be excluded
    :type exclude_through: bool
    :return: dictionary of table alias to label and allowed columns
    :rtype: dict[str, tuple[str, set[str]]]
    """
    tables: dict[str, tuple[str, type["Model"], set[str]]] = dict()
    for related in select_related:
        current_model, parent_str = model_cls, ""
        for relation in related.split("__"):
            field = cast(
                "ForeignKeyField", current_model.ormar_config.model_fields[relation]
            )
            related_str = f"{parent_str}__{relation}" if parent_str else relation
            parent_excludable = excludable.get(field.owner, alias=alias_for(parent_str))
            if field.is_multi and not exclude_through:
                through_name = field.through.get_name()
                through_alias = alias_for(f"{related_str}__{through_name}")
                tables[through_alias] = (
                    f"{parent_str}__{through_name}" if parent_str else through_name,
                    field.through,
                    allowed_columns(
                        model_cls=field.through,
                        excludable=excludable,
                        alias=through_alias,
                        is_excluded=parent_excludable.is_excluded(through_name),
                    ),
                )
            alias = alias_for(related_str)
            tables[alias] = (
                related_str,
                field.to,
                allowed_columns(
                    model_cls=field.to,
                    excludable=excludable,
                    alias=alias,
                    is_excluded=parent_excludable.is_excluded(field.name),
                ),
            )
            current_model, parent_str = field.to, related_str
    return tables

resolve_column(model_cls, column, allowed)

Parameters:

Name Type Description Default
model_cls type[Model]

model of the table the column belongs to

required
column str

database column name

required
allowed set[str]

names of the fields to return

required

Returns:

Type Description
list[ReturnedColumn]

the returned fields storing the column (several when fields share it), empty if none is returned

Source code in ormar/queryset/values_columns.py
Python
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
def resolve_column(
    model_cls: type["Model"], column: str, allowed: set[str]
) -> list[ReturnedColumn]:
    """
    :param model_cls: model of the table the column belongs to
    :type model_cls: type[Model]
    :param column: database column name
    :type column: str
    :param allowed: names of the fields to return
    :type allowed: set[str]
    :return: the returned fields storing the column (several when fields
        share it), empty if none is returned
    :rtype: list[ReturnedColumn]
    """
    resolved = []
    for field_name in model_cls.get_field_names_of_column(column=column):
        if field_name not in allowed:
            continue
        field = model_cls.ormar_config.model_fields.get(field_name)
        pairs = (
            cast("ForeignKeyField", field).link.pairs
            if field is not None and field.kind.holds_columns
            else ()
        )
        if len(pairs) > 1:
            part = next(
                pair.target_column for pair in pairs if pair.source_column == column
            )
            resolved.append(
                ReturnedColumn(
                    name=field_name,
                    relation=cast("ForeignKeyField", field),
                    part=part,
                )
            )
        else:
            resolved.append(ReturnedColumn(name=field_name))
    return resolved

values_column_map(model_cls, select_related, excludable, exclude_through, column_names)

Maps prefixed columns of a raw query to relation strings (relation names connected with dunders), skipping excluded columns.

Sample: translates: "t1a2b3c_name" -> into: "posts__user__name"

Parameters:

Name Type Description Default
model_cls type[Model]

main model of the query

required
select_related list[str]

list of related relation strings joined in the query

required
excludable ExcludableItems

structure of fields to include and exclude

required
exclude_through bool

flag if through models should be excluded

required
column_names list[str]

list of column names with prefixes from query

required

Returns:

Type Description
ValuesColumns

query columns and the names they are returned under

Source code in ormar/queryset/values_columns.py
Python
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
def values_column_map(
    model_cls: type["Model"],
    select_related: list[str],
    excludable: "ExcludableItems",
    exclude_through: bool,
    column_names: list[str],
) -> ValuesColumns:
    """
    Maps prefixed columns of a raw query to relation strings
    (relation names connected with dunders), skipping excluded columns.

    Sample: translates: "t1a2b3c_name" -> into: "posts__user__name"

    :param model_cls: main model of the query
    :type model_cls: type["Model"]
    :param select_related: list of related relation strings joined in the query
    :type select_related: list[str]
    :param excludable: structure of fields to include and exclude
    :type excludable: ExcludableItems
    :param exclude_through: flag if through models should be excluded
    :type exclude_through: bool
    :param column_names: list of column names with prefixes from query
    :type column_names: list[str]
    :return: query columns and the names they are returned under
    :rtype: ValuesColumns
    """
    tables = joined_table_columns(
        model_cls=model_cls,
        select_related=select_related,
        excludable=excludable,
        exclude_through=exclude_through,
    )
    own_columns = set(
        model_cls.own_table_columns(
            model=model_cls, excludable=excludable, add_pk_columns=False
        )
    )
    names: list[tuple[str, str]] = []
    key_parts: dict[tuple[str, str], ReturnedColumn] = dict()
    for column_name in column_names:
        prefix, _, column = column_name.partition("_")
        if prefix in tables:
            label, table_model, columns = tables[prefix]
            resolved = resolve_column(
                model_cls=table_model, column=column, allowed=columns
            )
            name_prefix = f"{label}__"
        else:
            resolved = resolve_column(
                model_cls=model_cls, column=column_name, allowed=own_columns
            )
            name_prefix = ""
        for returned in resolved:
            entry = (column_name, f"{name_prefix}{returned.name}")
            names.append(entry)
            if returned.relation is not None:
                key_parts[entry] = returned
    return ValuesColumns(names=tuple(names), key_parts=key_parts)