Skip to content

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

Merged
collerek merged 10 commits intomasterfrom
feature/flatten-fields
May 4, 2026
Merged

feat: add possibility to return primary keys instead of nested models, set by model incl. nesting#1641
collerek merged 10 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
}

@collerek collerek marked this pull request as ready for review April 29, 2026 07:58
@collerek collerek changed the title Add possibility to return primary keys instead of nested models, set by model incl. nesting feat: add possibility to return primary keys instead of nested models, set by model incl. nesting Apr 29, 2026
@codspeed-hq
Copy link
Copy Markdown

codspeed-hq Bot commented May 4, 2026

Merging this PR will degrade performance by 18.11%

❌ 1 (👁 1) regressed benchmark
✅ 83 untouched benchmarks

Performance Changes

Mode Benchmark BASE HEAD Efficiency
👁 WallTime test_making_and_inserting_models_in_bulk[10] 8.9 ms 10.9 ms -18.11%

Comparing feature/flatten-fields (80187d8) with master (672db74)

Open in CodSpeed

@collerek collerek merged commit 691e7d2 into master May 4, 2026
11 checks passed
@collerek collerek deleted the feature/flatten-fields branch May 4, 2026 10:22
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