fix: keep caller-supplied id when creating a model via auto_init (#8432)

This commit is contained in:
Vladimir Babin authored and GitHub committed 2026-09-16 21:55:34 +00:00
1 parent 6b247268fb
commit d1b02872ea
4 files changed
+52 -8

No files matched your search

+6 -7
View File
@@ -2,7 +2,7 @@ from functools import wraps
from uuid import UUID
from pydantic import BaseModel, ConfigDict, Field
from sqlalchemy import select
from sqlalchemy import inspect, select
from sqlalchemy.orm import MANYTOMANY, MANYTOONE, ONETOMANY, Session
from sqlalchemy.orm.mapper import Mapper
from sqlalchemy.orm.relationships import RelationshipProperty
@@ -26,9 +26,11 @@ class AutoInitConfig(BaseModel):
# auto_create: bool = False
def _get_config(relation_cls: type[SqlAlchemyBase]) -> AutoInitConfig:
def _get_config(relation_cls: type[SqlAlchemyBase], *, protect_primary_key: bool = True) -> AutoInitConfig:
"""
Returns the config for the given class.
`protect_primary_key` merges the default `{"id"}` exclusion into the model's own `exclude`.
"""
cfg = AutoInitConfig()
cfgKeys = cfg.model_dump().keys()
@@ -42,10 +44,7 @@ def _get_config(relation_cls: type[SqlAlchemyBase]) -> AutoInitConfig:
if attr not in cfgKeys:
continue
if attr == "exclude":
# A model's own `exclude` adds to the default exclusions (e.g. "id")
# rather than replacing them -- otherwise a model that declares
# `exclude` loses primary-key protection during `auto_init`.
if attr == "exclude" and protect_primary_key:
cfg.exclude = cfg.exclude | set(class_config[attr])
else:
setattr(cfg, attr, class_config[attr])
@@ -129,7 +128,7 @@ def auto_init(): # sourcery no-metrics
Ref: https://github.com/tiangolo/fastapi/issues/2194
"""
cls = self.__class__
config = _get_config(cls)
config = _get_config(cls, protect_primary_key=not inspect(self).transient)
exclude = config.exclude
alchemy_mapper: Mapper = self.__mapper__
@@ -242,7 +242,14 @@ def test_create_by_url_stream_done(
return Response(200, content=b"")
monkeypatch.setattr(AsyncSafeTransport, "handle_async_request", return_empty_response)
monkeypatch.setattr(RecipeDataService, "scrape_image", lambda *_: "TEST_IMAGE")
image_recipe_ids: list[str] = []
async def scrape_image(self: RecipeDataService, *_):
image_recipe_ids.append(str(self.recipe_id))
return "TEST_IMAGE"
monkeypatch.setattr(RecipeDataService, "scrape_image", scrape_image)
api_client.delete(api_routes.recipes_slug(recipe_data.expected_slug), headers=unique_user.token)
@@ -262,6 +269,9 @@ def test_create_by_url_stream_done(
assert any(e["event"] == "progress" for e in events)
recipe = api_client.get(api_routes.recipes_slug(recipe_data.expected_slug), headers=unique_user.token).json()
assert image_recipe_ids == [recipe["id"]]
def test_create_by_url_stream_error(
api_client: TestClient,
@@ -889,3 +889,33 @@ def test_recipe_note_step_references(unique_user: TestUser) -> None:
step = updated.recipe_instructions[0]
assert len(step.note_references) == 1
assert step.note_references[0].reference_id == reference_id
def test_recipe_create_keeps_provided_id(unique_user: TestUser) -> None:
recipe_id = uuid4()
recipe = unique_user.repos.recipes.create(
Recipe(
id=recipe_id,
user_id=unique_user.user_id,
group_id=unique_user.group_id,
name=random_string(),
)
)
assert recipe.id == recipe_id
def test_recipe_update_ignores_id_in_payload(unique_user: TestUser) -> None:
database = unique_user.repos
recipe = database.recipes.create(
Recipe(
user_id=unique_user.user_id,
group_id=unique_user.group_id,
name=random_string(),
)
)
updated = database.recipes.update(recipe.slug, recipe.model_copy(update={"id": None, "description": "changed"}))
assert updated.id == recipe.id
assert updated.description == "changed"
@@ -39,3 +39,8 @@ def test_get_config_preserves_default_exclude_for_unrelated_config_keys():
cfg = _get_config(_OtherConfigKeyOnly)
assert cfg.get_attr == "slug"
assert cfg.exclude == {"id"}
def test_get_config_without_primary_key_protection_uses_custom_exclude_as_is():
cfg = _get_config(_CustomExcludeOnly, protect_primary_key=False)
assert cfg.exclude == {"households_with_ingredient_food"}