Skip to content

Commit

Permalink
Allow id to be used as FK default (Fix #136)
Browse files Browse the repository at this point in the history
#117 introduced an issue for cases where `id` values is provided as a default for foreign keys.
This PR attempts to fix that issue by checking if generated value for FK field is an instance of this model - if not it uses `_id` as a field name (https://docs.djangoproject.com/en/3.1/ref/models/fields/#database-representation).
  • Loading branch information
Rust Saiargaliev committed Mar 9, 2021
1 parent 0a397a3 commit 035281c
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
13 changes: 13 additions & 0 deletions model_bakery/baker.py
Original file line number Diff line number Diff line change
Expand Up @@ -349,8 +349,21 @@ def _make(
self.m2m_dict[field.name] = self.m2m_value(field)
else:
self.m2m_dict[field.name] = self.model_attrs.pop(field.name)

elif field.name not in self.model_attrs:
if (
isinstance(field, ForeignKey)
and "{0}_id".format(field.name) not in self.model_attrs
):
value = self.generate_value(field, commit_related)
if isinstance(value, field.related_model):
field_name = field.name
else:
field_name = "{0}_id".format(field.name)

self.model_attrs[field_name] = value

elif (
not isinstance(field, ForeignKey)
or "{0}_id".format(field.name) not in self.model_attrs
):
Expand Down
17 changes: 17 additions & 0 deletions tests/generic/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,23 @@ class DummyGenericRelationModel(models.Model):
relation = GenericRelation(DummyGenericForeignKeyModel)


class NamedThing(models.Model):
name = models.CharField(max_length=64)


def get_default_namedthing_id():
instance, _ = NamedThing.objects.get_or_create(name="Default")
return instance.id


class DummyForeignKeyWithDefaultIdModel(models.Model):
named_thing = models.ForeignKey(
"NamedThing",
default=get_default_namedthing_id,
on_delete=models.SET_DEFAULT,
)


class DummyNullFieldsModel(models.Model):
null_foreign_key = models.ForeignKey(
"DummyBlankFieldsModel", null=True, on_delete=models.CASCADE
Expand Down
9 changes: 9 additions & 0 deletions tests/test_filling_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,15 @@ def test_filling_content_type_field(self):
assert dummy.content_type.model_class() is not None


@pytest.mark.django_db
class TestFillingForeignKeyFieldWithDefaultFunctionReturningId:
def test_filling_foreignkey_with_default_id(self):
dummy = baker.make(
models.DummyForeignKeyWithDefaultIdModel, named_thing__name="Default"
)
assert dummy.named_thing.id == models.get_default_namedthing_id()


@pytest.mark.django_db
class TestsFillingFileField:
def test_filling_file_field(self):
Expand Down

0 comments on commit 035281c

Please sign in to comment.