Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Raise exception on ambiguous model name.

If 2 apps have models with the same name we can't
get the model without the app name.
  • Loading branch information...
commit 858031b44228c7c9f7b80ac09aa426da3614efac 1 parent e8dc7ee
@henriquebastos henriquebastos authored
View
20 model_mommy/mommy.py
@@ -115,6 +115,11 @@ def make_many_from_recipe(mommy_recipe_name, quantity=None, **new_attrs):
class ModelNotFound(Exception):
pass
+
+class AmbiguousModelName(Exception):
+ pass
+
+
class Mommy(object):
attr_mapping = {}
type_mapping = None
@@ -136,14 +141,25 @@ def __init__(self, model, make_m2m=True):
def _get_model(self, name):
'''
- Return the first model found.
+ Get a model by name.
+
+ If a model with that name exists in more than one app,
+ raises AmbiguousModelNameException.
'''
name = name.lower()
+ model = None
for app_model in cache.app_models.values():
for n, m in app_model.items():
if name == n:
- return m
+ if model:
+ raise AmbiguousModelName('%s is a model in more than one app. '
+ 'Use the form "app.model".' % name.title())
+ else:
+ model = m
+
+ return model
+
def make_one(self, **attrs):
'''Creates and persists an instance of the model
View
1  runtests.py
@@ -28,6 +28,7 @@ def configure_settings(options):
INSTALLED_APPS = (
'django.contrib.contenttypes',
'test.generic',
+ 'test.ambiguous',
),
SITE_ID=1,
TEST_ROOT=join(dirname(__file__), 'test', 'generic', 'tests'),
View
1  test/ambiguous/__init__.py
@@ -0,0 +1 @@
+# coding: utf-8
View
6 test/ambiguous/models.py
@@ -0,0 +1,6 @@
+# coding: utf-8
+from django.db import models
+
+
+class Ambiguous(models.Model):
+ name = models.CharField(max_length=20)
View
4 test/generic/models.py
@@ -143,3 +143,7 @@ class DummyFileFieldModel(models.Model):
class DummyImageFieldModel(models.Model):
fs = FileSystemStorage(location='/tmp/')
image_field = models.ImageField(upload_to="%Y/%m/%d", storage=fs)
+
+
+class Ambiguous(models.Model):
+ name = models.CharField(max_length=20)
View
6 test/generic/tests/test_mommy.py
@@ -4,7 +4,7 @@
from django.test import TestCase
from model_mommy import mommy
-from model_mommy.mommy import ModelNotFound
+from model_mommy.mommy import ModelNotFound, AmbiguousModelName
from model_mommy.timezone import smart_datetime as datetime
from test.generic.models import Person, Dog, Store, LonelyPerson
from test.generic.models import User, PaymentBill
@@ -31,6 +31,10 @@ def test_model_string(self):
obj = mommy.prepare_one('Person')
self.assertIsInstance(obj, Person)
+ def test_raise_on_ambiguous_model_string(self):
+ with self.assertRaises(AmbiguousModelName):
+ obj = mommy.prepare_one('Ambiguous')
+
class MommyCreatesSimpleModel(TestCase):
Please sign in to comment.
Something went wrong with that request. Please try again.