Permalink
Browse files

Add support to load models without app name

  • Loading branch information...
1 parent e0bf4ee commit e8dc7eed2291ebb85881a96601d118f1e25897b7 @henriquebastos henriquebastos committed Jan 4, 2013
Showing with 22 additions and 2 deletions.
  1. +18 −2 model_mommy/mommy.py
  2. +4 −0 test/generic/tests/test_mommy.py
View
20 model_mommy/mommy.py
@@ -2,6 +2,7 @@
from django.utils import importlib
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
+from django.db.models.loading import cache
from django.db.models import (\
CharField, EmailField, SlugField, TextField, URLField,
DateField, DateTimeField, TimeField,
@@ -122,13 +123,28 @@ def __init__(self, model, make_m2m=True):
self.make_m2m = make_m2m
self.type_mapping = default_mapping.copy()
if isinstance(model, basestring):
- app_label, model_name = model.split('.')
- self.model = get_model(app_label, model_name)
+ if '.' in model:
+ app_label, model_name = model.split('.')
+ self.model = get_model(app_label, model_name)
+ else:
+ self.model = self._get_model(model)
if not self.model:
raise ModelNotFound("could not find model '%s' in the app '%s'." %(model_name, app_label))
else:
self.model = model
+
+ def _get_model(self, name):
+ '''
+ Return the first model found.
+ '''
+ name = name.lower()
+
+ for app_model in cache.app_models.values():
+ for n, m in app_model.items():
+ if name == n:
+ return m
+
def make_one(self, **attrs):
'''Creates and persists an instance of the model
associated with Mommy instance.'''
View
4 test/generic/tests/test_mommy.py
@@ -27,6 +27,10 @@ def test_app_model_string(self):
obj = mommy.prepare_one('generic.Person')
self.assertIsInstance(obj, Person)
+ def test_model_string(self):
+ obj = mommy.prepare_one('Person')
+ self.assertIsInstance(obj, Person)
+
class MommyCreatesSimpleModel(TestCase):

0 comments on commit e8dc7ee

Please sign in to comment.