Fixed #12168 -- Corrected the registration of m2m autocreated models when models.py is split into submodules. Thanks to Jens Diemer for the report and test case.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@11724 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Russell Keith-Magee 2009-11-05 11:57:28 +00:00
parent 77abadfa6a
commit 7b63d3d3b4
6 changed files with 65 additions and 1 deletions

View File

@ -829,9 +829,18 @@ def create_many_to_many_intermediary_model(field, klass):
'auto_created': klass, 'auto_created': klass,
'unique_together': (from_, to) 'unique_together': (from_, to)
}) })
# If the models have been split into subpackages, klass.__module__
# will be the subpackge, not the models module for the app. (See #12168)
# Compose the actual models module name by stripping the trailing parts
# of the namespace until we find .models
parts = klass.__module__.split('.')
while parts[-1] != 'models':
parts.pop()
module = '.'.join(parts)
# Construct and return the new class.
return type(name, (models.Model,), { return type(name, (models.Model,), {
'Meta': meta, 'Meta': meta,
'__module__': klass.__module__, '__module__': module,
from_: models.ForeignKey(klass, related_name='%s+' % name), from_: models.ForeignKey(klass, related_name='%s+' % name),
to: models.ForeignKey(to_model, related_name='%s+' % name) to: models.ForeignKey(to_model, related_name='%s+' % name)
}) })

View File

@ -0,0 +1 @@

View File

@ -0,0 +1,3 @@
# Import all the models from subpackages
from article import Article
from publication import Publication

View File

@ -0,0 +1,10 @@
from django.db import models
from django.contrib.sites.models import Site
class Article(models.Model):
sites = models.ManyToManyField(Site)
headline = models.CharField(max_length=100)
publications = models.ManyToManyField("model_package.Publication", null=True, blank=True,)
class Meta:
app_label = 'model_package'

View File

@ -0,0 +1,7 @@
from django.db import models
class Publication(models.Model):
title = models.CharField(max_length=30)
class Meta:
app_label = 'model_package'

View File

@ -0,0 +1,34 @@
"""
>>> from models.publication import Publication
>>> from models.article import Article
>>> from django.contrib.auth.views import Site
>>> p = Publication(title="FooBar")
>>> p.save()
>>> p
<Publication: Publication object>
>>> from django.contrib.sites.models import Site
>>> current_site = Site.objects.get_current()
>>> current_site
<Site: example.com>
# Regression for #12168: models split into subpackages still get M2M tables
>>> a = Article(headline="a foo headline")
>>> a.save()
>>> a.publications.add(p)
>>> a.sites.add(current_site)
>>> a.save()
>>> a = Article.objects.get(id=1)
>>> a
<Article: Article object>
>>> a.id
1
>>> a.sites.count()
1
"""