Skip to content

Commit

Permalink
Fix forward M2M relation dependency.
Browse files Browse the repository at this point in the history
  • Loading branch information
K0Te committed Oct 6, 2018
1 parent cfb15fd commit 75c8e94
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 8 deletions.
13 changes: 13 additions & 0 deletions django_object_manager/object_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,8 @@ def cb(field, field_val, instance):
args = \
{instance._meta.model.__name__.lower(): instance,
field.related_model.__name__.lower(): field_val}
# Create dependency after main object, using
# M2M "through" model
field.through(**args).save()
for related_val in params.pop(field.name):
post_add.append(partial(cb, field, related_val))
Expand All @@ -105,9 +107,19 @@ def cb(field_val, instance):
setattr(field_val,
instance._meta.model.__name__.lower(),
instance)
# Delay 1-to-1 dependency object creation
field_val.save()
val = params.pop(field.name)
post_add.append(partial(cb, val))
elif isinstance(field, ManyToManyField):
def cb(field, field_val, instance):
field_val.save()
# Delay forward M2M dependency,
# use RelatedManager helper
# TODO no related manager if `through` model has extra attributes ?
getattr(instance, field.name).add(field_val)
for related_val in params.pop(field.name):
post_add.append(partial(cb, field, related_val))
return post_add

def _get_or_create(self, _name, _key, _create_in_db=True, _custom=False,
Expand All @@ -118,6 +130,7 @@ def _get_or_create(self, _name, _key, _create_in_db=True, _custom=False,
return instance
post_add = self._create_dependencies(model, kwargs)
if _create_in_db:
print('###: ', kwargs)
instance = model(**kwargs)
instance.save(force_insert=True)
else:
Expand Down
17 changes: 9 additions & 8 deletions tests/functional/test_object_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,13 +79,14 @@ def test_many_to_many_reversed_predefined(self):
films=[film1, film2])
self.assertEqual(models.FilmCategory.objects.count(), 1)

# def test_many_to_many_forward_predefined(self):
# """Ensure that object with M2M relation can be created."""
# film = self.object_manager.get_film(name='Memento',
# year=2000,
# uploaded_by='bob',
# categories=['crime', 'drama'])
# self.assertEqual(models.FilmCategory.objects.count(), 2)
#
def test_many_to_many_forward_predefined(self):
"""Ensure that object with M2M relation can be created."""
film = self.object_manager.get_film(name='Memento',
year=2000,
uploaded_by='bob',
categories=['crime', 'drama'])
self.assertEqual(models.FilmCategory.objects.count(), 2)

# TODO
# def test_customized(self):
# """Ensure that customized objects are not cached."""

0 comments on commit 75c8e94

Please sign in to comment.