From 5f4354d4451b08cdff5b977160cc18b050178073 Mon Sep 17 00:00:00 2001 From: collerek Date: Sun, 24 Mar 2024 00:41:32 +0100 Subject: [PATCH] port #989 to new branch due to lack of perms to fix conflicts (#1276) --- ormar/fields/foreign_key.py | 4 ++- .../test_model_definition.py | 25 +++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/ormar/fields/foreign_key.py b/ormar/fields/foreign_key.py index d347454..4c8f602 100644 --- a/ormar/fields/foreign_key.py +++ b/ormar/fields/foreign_key.py @@ -262,6 +262,8 @@ def ForeignKey( # type: ignore # noqa CFQ002 sql_nullable = kwargs.pop("sql_nullable", None) sql_nullable = nullable if sql_nullable is None else sql_nullable + index = kwargs.pop("index", False) + validate_not_allowed_fields(kwargs) pk_only_model = None if to.__class__ == ForwardRef: @@ -296,7 +298,7 @@ def ForeignKey( # type: ignore # noqa CFQ002 related_name=related_name, virtual=virtual, primary_key=False, - index=False, + index=index, default=None, server_default=None, onupdate=onupdate, diff --git a/tests/test_model_definition/test_model_definition.py b/tests/test_model_definition/test_model_definition.py index d3ca604..f8457c0 100644 --- a/tests/test_model_definition/test_model_definition.py +++ b/tests/test_model_definition/test_model_definition.py @@ -54,6 +54,26 @@ class ExampleModel2(Model): test_string: str = ormar.String(max_length=250) +class User(ormar.Model): + ormar_config = base_ormar_config.copy(tablename="users") + + id: int = ormar.Integer(primary_key=True) + + +class Account(ormar.Model): + ormar_config = base_ormar_config.copy(tablename="accounts") + + id: int = ormar.Integer(primary_key=True) + user: User = ormar.ForeignKey(User, index=False) + + +class Purchase(ormar.Model): + ormar_config = base_ormar_config.copy(tablename="purchases") + + id: int = ormar.Integer(primary_key=True) + user: User = ormar.ForeignKey(User, index=True) + + create_test_database = init_tests(base_ormar_config) @@ -218,3 +238,8 @@ def test_json_conversion_in_model(): test_string="test", test_bool=True, ) + + +def test_foreign_key_index(): + assert Account.ormar_config.table.columns.user.index is False + assert Purchase.ormar_config.table.columns.user.index is True