Skip to content

Commit

Permalink
Fix #492 -- Allow prepare() to be used with GFK (#495)
Browse files Browse the repository at this point in the history
  • Loading branch information
amureki authored Aug 16, 2024
1 parent e2913a8 commit 10e53f5
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 4 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).

### Changed
- Align GFK and content type fields generation
- Allow `prepare()` to be used with GFK

### Removed

Expand Down
7 changes: 5 additions & 2 deletions model_bakery/baker.py
Original file line number Diff line number Diff line change
Expand Up @@ -526,11 +526,13 @@ def instance(
}

instance = self.model(**attrs)

self._handle_generic_foreign_keys(instance, generic_foreign_keys)

if _commit:
instance.save(**_save_kwargs)
self._handle_one_to_many(instance, one_to_many_keys)
self._handle_m2m(instance)
self._handle_generic_foreign_keys(instance, generic_foreign_keys)
self._handle_auto_now(instance, auto_now_keys)

if _from_manager:
Expand Down Expand Up @@ -692,13 +694,14 @@ def _handle_m2m(self, instance: Model):

def _handle_generic_foreign_keys(self, instance: Model, attrs: Dict[str, Any]):
"""Set content type and object id for GenericForeignKey fields."""
for _field_name, data in attrs.items():
for field_name, data in attrs.items():
content_type_field = data["content_type_field"]
object_id_field = data["object_id_field"]
value = data["value"]
if is_iterator(value):
value = next(value)

setattr(instance, field_name, value)
setattr(
instance,
content_type_field,
Expand Down
18 changes: 16 additions & 2 deletions tests/test_filling_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -287,12 +287,26 @@ def test_filling_content_type_field(self):
def test_filling_from_content_object(self):
from django.contrib.contenttypes.models import ContentType

profile = baker.make(models.Profile)
dummy = baker.make(
models.DummyGenericForeignKeyModel,
content_object=baker.make(models.Profile),
content_object=profile,
)
assert dummy.content_object == profile
assert dummy.content_type == ContentType.objects.get_for_model(models.Profile)
assert dummy.object_id == models.Profile.objects.get().pk
assert dummy.object_id == profile.pk

def test_filling_generic_foreign_key_field_with_prepare(self):
from django.contrib.contenttypes.models import ContentType

profile = baker.prepare(models.Profile, id=1)
dummy = baker.prepare(
models.DummyGenericForeignKeyModel,
content_object=profile,
)
assert dummy.content_object == profile
assert dummy.content_type == ContentType.objects.get_for_model(models.Profile)
assert dummy.object_id == profile.pk == 1

def test_iteratively_filling_generic_foreign_key_field(self):
"""
Expand Down

0 comments on commit 10e53f5

Please sign in to comment.