Skip to content

Add possibility to return primary keys instead of nested models, set by model incl. nesting#1641

Draft
collerek wants to merge 3 commits intomasterfrom
feature/flatten-fields
Draft

Add possibility to return primary keys instead of nested models, set by model incl. nesting#1641
collerek wants to merge 3 commits intomasterfrom
feature/flatten-fields

Conversation

@collerek
Copy link
Copy Markdown
Collaborator

flatten_fields

flatten_fields(columns: Union[list, str, set, tuple, dict, FieldAccessor]) -> QuerySet

With flatten_fields() you can render selected related models as their primary
key value on model_dump() instead of the default nested dict. This is useful
when your API clients expect {"manufacturer": 1} rather than
{"manufacturer": {"id": 1, "name": "Toyota", ...}}.

Accepts the same input forms as fields() / exclude_fields() (string, list,
set, tuple, dict-with-Ellipsis) plus FieldAccessor / list of accessors.
Works across foreign keys, many-to-many, and reverse relations.

all_cars = await (
    Car.objects
    .select_related('manufacturer')
    .flatten_fields('manufacturer')
    .all()
)
assert all_cars[0].model_dump() == {
    'id': 1,
    'name': 'Corolla',
    'manufacturer': 1,  # flattened from nested dict to pk value
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant