From c5b28b89002950151c4848aeaa115a99d05b7c09 Mon Sep 17 00:00:00 2001 From: Terrence Dorsey Date: Sat, 8 Jul 2023 04:27:12 -0400 Subject: [PATCH] Document `alias_priority` (#6520) --- docs/usage/fields.md | 14 ++++++++------ docs/usage/model_config.md | 10 +++++++++- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/docs/usage/fields.md b/docs/usage/fields.md index 27e6e66148..eabde84041 100644 --- a/docs/usage/fields.md +++ b/docs/usage/fields.md @@ -119,12 +119,15 @@ print(user.model_dump(by_alias=True)) # (2)! 1. The field name `'name'` is used for validation. 2. The serialization alias `'username'` is used for serialization. -In case you use `alias` together with `validation_alias` or `serialization_alias` at the same time, -the `validation_alias` will have priority over `alias` for validation, and `serialization_alias` will have priority -over `alias` for serialization. +!!! note "Alias precedence and priority" + In case you use `alias` together with `validation_alias` or `serialization_alias` at the same time, + the `validation_alias` will have priority over `alias` for validation, and `serialization_alias` will have priority + over `alias` for serialization. -You can read more about [Alias Precedence](model_config.md#alias-precedence) in the -[Model Config](model_config.md) documentation. + You may also set `alias_priority` on a field to change this behavior. + + You can read more about [Alias Precedence](model_config.md#alias-precedence) in the + [Model Config](model_config.md) documentation. ??? tip "VSCode and Pyright users" @@ -734,7 +737,6 @@ print(User.model_json_schema()) """ ``` -TODO: Add `alias_priority` parameters. [JSON Schema Draft 2020-12]: https://json-schema.org/understanding-json-schema/reference/numeric.html#numeric-types [Discriminated Unions]: types/unions.md#discriminated-unions-aka-tagged-unions diff --git a/docs/usage/model_config.md b/docs/usage/model_config.md index 29057a8c84..e76d3a4b7e 100644 --- a/docs/usage/model_config.md +++ b/docs/usage/model_config.md @@ -180,7 +180,7 @@ instead use the `to_lower_camel` function. ## Alias Precedence -If you specify an `alias` on the `Field`, it will take precedence over the generated alias: +If you specify an `alias` on the `Field`, it will take precedence over the generated alias by default: ```py from pydantic import BaseModel, ConfigDict, Field @@ -204,6 +204,14 @@ print(voice.model_dump(by_alias=True)) #> {'Name': 'Filiz', 'lang': 'tr-TR'} ``` +### Alias Priority + +You may set `alias_priority` on a field to change this behavior: + +* `alias_priority=2` the alias will *not* be overridden by the alias generator. +* `alias_priority=1` the alias *will* be overridden by the alias generator. +* `alias_priority` not set, the alias will be overridden by the alias generator. + The same precedence applies to `validation_alias` and `serialization_alias`. See more about the different field aliases under [field aliases](fields.md#field-aliases).