Skip to content
Browse files

Merge pull request #133 from berinhard/bugfix/many2many-with-default-…

…true

Bugfix to handle creation of nullables ManyToManyField
  • Loading branch information...
2 parents 8414e08 + 1a5067e commit 0b8a078f674a8967983ecf9230961df569cbad27 @vandersonmota committed
Showing with 17 additions and 4 deletions.
  1. +4 −3 model_mommy/mommy.py
  2. +4 −0 test/generic/models.py
  3. +9 −1 test/generic/tests/test_mommy.py
View
7 model_mommy/mommy.py
@@ -281,10 +281,11 @@ def _make(self, commit=True, **attrs):
return self.instance(model_attrs, _commit=commit)
def m2m_value(self, field):
- if not (self.make_m2m or field.null) and field.name not in self.rel_fields:
- return []
- else:
+ if field.name in self.rel_fields:
return self.generate_value(field)
+ if not self.make_m2m or field.null:
+ return []
+ return self.generate_value(field)
def instance(self, attrs, _commit):
instance = self.model(**attrs)
View
4 test/generic/models.py
@@ -70,6 +70,10 @@ class LonelyPerson(models.Model):
only_friend = models.OneToOneField(Person)
+class Classroom(models.Model):
+ students = models.ManyToManyField(Person, null=True)
+
+
class Store(models.Model):
customers = models.ManyToManyField(Person, related_name='favorite_stores')
employees = models.ManyToManyField(Person, related_name='employers')
View
10 test/generic/tests/test_mommy.py
@@ -10,7 +10,7 @@
from model_mommy import mommy
from model_mommy.exceptions import ModelNotFound, AmbiguousModelName, InvalidQuantityException
from model_mommy.timezone import smart_datetime as datetime
-from test.generic.models import Person, Dog, Store, LonelyPerson, School, SchoolEnrollment, ModelWithImpostorField
+from test.generic.models import Person, Dog, Store, LonelyPerson, School, SchoolEnrollment, ModelWithImpostorField, Classroom
from test.generic.models import User, PaymentBill
from test.generic.models import UnsupportedModel, DummyGenericRelationModel
from test.generic.models import DummyNullFieldsModel, DummyBlankFieldsModel
@@ -208,6 +208,14 @@ def test_does_not_create_many_to_many_as_default(self):
self.assertEqual(store.employees.count(), 0)
self.assertEqual(store.customers.count(), 0)
+ def test_does_not_create_nullable_many_to_many_for_relations(self):
+ classroom = mommy.make(Classroom, make_m2m=False)
+ self.assertEqual(classroom.students.count(), 0)
+
+ def test_nullable_many_to_many_is_not_created_even_if_flagged(self):
+ classroom = mommy.make(Classroom, make_m2m=True)
+ self.assertEqual(classroom.students.count(), 0)
+
def test_simple_creating_person_with_parameters(self):
kid = mommy.make(Person, happy=True, age=10, name='Mike')
self.assertEqual(kid.age, 10)

0 comments on commit 0b8a078

Please sign in to comment.
Something went wrong with that request. Please try again.