Kaydet (Commit) 174641b9 authored tarafından Russell Keith-Magee's avatar Russell Keith-Magee

Fixed #6095 -- Added the ability to specify the model to use to manage a…

Fixed #6095 -- Added the ability to specify the model to use to manage a ManyToManyField. Thanks to Eric Florenzano for his excellent work on this patch.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@8136 bcc190cf-cafb-0310-a4f2-bffc1f526a37
üst f752f692
......@@ -154,6 +154,7 @@ answer newbie questions, and generally made Django that much better:
Maciej Fijalkowski
Matthew Flanagan <http://wadofstuff.blogspot.com>
Eric Floehr <eric@intellovations.com>
Eric Florenzano <floguy@gmail.com>
Vincent Foley <vfoleybourgon@yahoo.ca>
Rudolph Froger <rfroger@estrate.nl>
Jorge Gajon <gajon@gajon.org>
......
......@@ -161,7 +161,10 @@ class BaseModelAdmin(object):
kwargs['empty_label'] = db_field.blank and _('None') or None
else:
if isinstance(db_field, models.ManyToManyField):
if db_field.name in self.raw_id_fields:
# If it uses an intermediary model, don't show field in admin.
if db_field.rel.through is not None:
return None
elif db_field.name in self.raw_id_fields:
kwargs['widget'] = widgets.ManyToManyRawIdWidget(db_field.rel)
kwargs['help_text'] = ''
elif db_field.name in (list(self.filter_vertical) + list(self.filter_horizontal)):
......
......@@ -104,6 +104,9 @@ class GenericRelation(RelatedField, Field):
limit_choices_to=kwargs.pop('limit_choices_to', None),
symmetrical=kwargs.pop('symmetrical', True))
# By its very nature, a GenericRelation doesn't create a table.
self.creates_table = False
# Override content-type/object-id field names on the related class
self.object_id_field_name = kwargs.pop("object_id_field", "object_id")
self.content_type_field_name = kwargs.pop("content_type_field", "content_type")
......
......@@ -353,7 +353,7 @@ def many_to_many_sql_for_model(model, style):
qn = connection.ops.quote_name
inline_references = connection.features.inline_fk_references
for f in opts.local_many_to_many:
if not isinstance(f.rel, generic.GenericRel):
if f.creates_table:
tablespace = f.db_tablespace or opts.db_tablespace
if tablespace and connection.features.supports_tablespaces:
tablespace_sql = ' ' + connection.ops.tablespace_sql(tablespace, inline=True)
......
......@@ -102,6 +102,7 @@ def get_validation_errors(outfile, app=None):
if r.get_accessor_name() == rel_query_name:
e.add(opts, "Reverse query name for field '%s' clashes with related field '%s.%s'. Add a related_name argument to the definition for '%s'." % (f.name, rel_opts.object_name, r.get_accessor_name(), f.name))
seen_intermediary_signatures = []
for i, f in enumerate(opts.local_many_to_many):
# Check to see if the related m2m field will clash with any
# existing fields, m2m fields, m2m related objects or related
......@@ -112,7 +113,49 @@ def get_validation_errors(outfile, app=None):
# so skip the next section
if isinstance(f.rel.to, (str, unicode)):
continue
if getattr(f.rel, 'through', None) is not None:
if hasattr(f.rel, 'through_model'):
from_model, to_model = cls, f.rel.to
if from_model == to_model and f.rel.symmetrical:
e.add(opts, "Many-to-many fields with intermediate tables cannot be symmetrical.")
seen_from, seen_to, seen_self = False, False, 0
for inter_field in f.rel.through_model._meta.fields:
rel_to = getattr(inter_field.rel, 'to', None)
if from_model == to_model: # relation to self
if rel_to == from_model:
seen_self += 1
if seen_self > 2:
e.add(opts, "Intermediary model %s has more than two foreign keys to %s, which is ambiguous and is not permitted." % (f.rel.through_model._meta.object_name, from_model._meta.object_name))
else:
if rel_to == from_model:
if seen_from:
e.add(opts, "Intermediary model %s has more than one foreign key to %s, which is ambiguous and is not permitted." % (f.rel.through_model._meta.object_name, rel_from._meta.object_name))
else:
seen_from = True
elif rel_to == to_model:
if seen_to:
e.add(opts, "Intermediary model %s has more than one foreign key to %s, which is ambiguous and is not permitted." % (f.rel.through_model._meta.object_name, rel_to._meta.object_name))
else:
seen_to = True
if f.rel.through_model not in models.get_models():
e.add(opts, "'%s' specifies an m2m relation through model %s, which has not been installed." % (f.name, f.rel.through))
signature = (f.rel.to, cls, f.rel.through_model)
if signature in seen_intermediary_signatures:
e.add(opts, "The model %s has two manually-defined m2m relations through the model %s, which is not permitted. Please consider using an extra field on your intermediary model instead." % (cls._meta.object_name, f.rel.through_model._meta.object_name))
else:
seen_intermediary_signatures.append(signature)
seen_related_fk, seen_this_fk = False, False
for field in f.rel.through_model._meta.fields:
if field.rel:
if not seen_related_fk and field.rel.to == f.rel.to:
seen_related_fk = True
elif field.rel.to == cls:
seen_this_fk = True
if not seen_related_fk or not seen_this_fk:
e.add(opts, "'%s' has a manually-defined m2m relation through model %s, which does not have foreign keys to %s and %s" % (f.name, f.rel.through, f.rel.to._meta.object_name, cls._meta.object_name))
else:
e.add(opts, "'%s' specifies an m2m relation through model %s, which has not been installed" % (f.name, f.rel.through))
rel_opts = f.rel.to._meta
rel_name = RelatedObject(f.rel.to, cls, f).get_accessor_name()
rel_query_name = f.related_query_name()
......
......@@ -617,6 +617,61 @@ automatically::
FriendshipInline,
]
Working with Many-to-Many Intermediary Models
----------------------------------------------
By default, admin widgets for many-to-many relations will be displayed inline
on whichever model contains the actual reference to the `ManyToManyField`.
However, when you specify an intermediary model using the ``through``
argument to a ``ManyToManyField``, the admin will not display a widget by
default. This is because each instance of that intermediary model requires
more information than could be displayed in a single widget, and the layout
required for multiple widgets will vary depending on the intermediate model.
However, we still want to be able to edit that information inline. Fortunately,
this is easy to do with inline admin models. Suppose we have the following
models::
class Person(models.Model):
name = models.CharField(max_length=128)
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person, through='Membership')
class Membership(models.Model):
person = models.ForeignKey(Person)
group = models.ForeignKey(Group)
date_joined = models.DateField()
invite_reason = models.CharField(max_length=64)
The first step in displaying this intermediate model in the admin is to
define an inline model for the Membership table::
class MembershipInline(admin.TabularInline):
model = Membership
extra = 1
This simple example uses the defaults inline form for the Membership model,
and shows 1 extra line. This could be customized using any of the options
available to inline models.
Now create admin views for the ``Person`` and ``Group`` models::
class PersonAdmin(admin.ModelAdmin):
inlines = (MembershipInline,)
class GroupAdmin(admin.ModelAdmin):
inlines = (MembershipInline,)
Finally, register your ``Person`` and ``Group`` models with the admin site::
admin.site.register(Person, PersonAdmin)
admin.site.register(Group, GroupAdmin)
Now your admin site is set up to edit ``Membership`` objects inline from either
the ``Person`` or the ``Group`` detail pages.
``AdminSite`` objects
=====================
......
......@@ -655,7 +655,7 @@ Note that this value is *not* HTML-escaped when it's displayed in the admin
interface. This lets you include HTML in ``help_text`` if you so desire. For
example::
help_text="Please use the following format: <em>YYYY-MM-DD</em>."
help_text="Please use the following format: <em>YYYY-MM-DD</em>."
Alternatively you can use plain text and
``django.utils.html.escape()`` to escape any HTML special characters.
......@@ -944,6 +944,131 @@ the relationship should work. All are optional:
======================= ============================================================
Extra fields on many-to-many relationships
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
**New in Django development version**
When you're only dealing with simple many-to-many relationships such as
mixing and matching pizzas and toppings, a standard ``ManyToManyField``
is all you need. However, sometimes you may need to associate data with the
relationship between two models.
For example, consider the case of an application tracking the musical groups
which musicians belong to. There is a many-to-many relationship between a person
and the groups of which they are a member, so you could use a ManyToManyField
to represent this relationship. However, there is a lot of detail about the
membership that you might want to collect, such as the date at which the person
joined the group.
For these situations, Django allows you to specify the model that will be used
to govern the many-to-many relationship. You can then put extra fields on the
intermediate model. The intermediate model is associated with the
``ManyToManyField`` using the ``through`` argument to point to the model
that will act as an intermediary. For our musician example, the code would look
something like this::
class Person(models.Model):
name = models.CharField(max_length=128)
def __unicode__(self):
return self.name
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person, through='Membership')
def __unicode__(self):
return self.name
class Membership(models.Model):
person = models.ForeignKey(Person)
group = models.ForeignKey(Group)
date_joined = models.DateField()
invite_reason = models.CharField(max_length=64)
When you set up the intermediary model, you explicitly specify foreign
keys to the models that are involved in the ManyToMany relation. This
explicit declaration defines how the two models are related.
There are a few restrictions on the intermediate model:
* Your intermediate model must contain one - and *only* one - foreign key
on the target model (this would be ``Person`` in our example). If you
have more than one foreign key, a validation error will be raised.
* Your intermediate model must contain one - and *only* one - foreign key
on the source model (this would be ``Group`` in our example). If you
have more than one foreign key, a validation error will be raised.
* If the many-to-many relation is a relation on itself, the relationship
must be non-symmetric.
Now that you have set up your ``ManyToManyField`` to use your intermediary
model (Membership, in this case), you're ready to start creating some
many-to-many relationships. You do this by creating instances of the
intermediate model::
>>> ringo = Person.objects.create(name="Ringo Starr")
>>> paul = Person.objects.create(name="Paul McCartney")
>>> beatles = Group.objects.create(name="The Beatles")
>>> m1 = Membership(person=ringo, group=beatles,
... date_joined=date(1962, 8, 16),
... invite_reason= "Needed a new drummer.")
>>> m1.save()
>>> beatles.members.all()
[<Person: Ringo Starr>]
>>> ringo.group_set.all()
[<Group: The Beatles>]
>>> m2 = Membership.objects.create(person=paul, group=beatles,
... date_joined=date(1960, 8, 1),
... invite_reason= "Wanted to form a band.")
>>> beatles.members.all()
[<Person: Ringo Starr>, <Person: Paul McCartney>]
Unlike normal many-to-many fields, you *can't* use ``add``, ``create``,
or assignment (i.e., ``beatles.members = [...]``) to create relationships::
# THIS WILL NOT WORK
>>> beatles.members.add(john)
# NEITHER WILL THIS
>>> beatles.members.create(name="George Harrison")
# AND NEITHER WILL THIS
>>> beatles.members = [john, paul, ringo, george]
Why? You can't just create a relationship between a Person and a Group - you
need to specify all the detail for the relationship required by the
Membership table. The simple ``add``, ``create`` and assignment calls
don't provide a way to specify this extra detail. As a result, they are
disabled for many-to-many relationships that use an intermediate model.
The only way to create a many-to-many relationship with an intermediate table
is to create instances of the intermediate model.
The ``remove`` method is disabled for similar reasons. However, the
``clear()`` method can be used to remove all many-to-many relationships
for an instance::
# Beatles have broken up
>>> beatles.members.clear()
Once you have established the many-to-many relationships by creating instances
of your intermediate model, you can issue queries. Just as with normal
many-to-many relationships, you can query using the attributes of the
many-to-many-related model::
# Find all the groups with a member whose name starts with 'Paul'
>>> Groups.objects.filter(person__name__startswith='Paul')
[<Group: The Beatles>]
As you are using an intermediate table, you can also query on the attributes
of the intermediate model::
# Find all the members of the Beatles that joined after 1 Jan 1961
>>> Person.objects.filter(
... group__name='The Beatles',
... membership__date_joined__gt=date(1961,1,1))
[<Person: Ringo Starr]
One-to-one relationships
~~~~~~~~~~~~~~~~~~~~~~~~
......@@ -1145,7 +1270,7 @@ any parent classes in ``unique_together``.
For convenience, unique_together can be a single list when dealing
with a single set of fields::
unique_together = ("driver", "restaurant")
unique_together = ("driver", "restaurant")
``verbose_name``
----------------
......
......@@ -110,6 +110,63 @@ class Car(models.Model):
class MissingRelations(models.Model):
rel1 = models.ForeignKey("Rel1")
rel2 = models.ManyToManyField("Rel2")
class MissingManualM2MModel(models.Model):
name = models.CharField(max_length=5)
missing_m2m = models.ManyToManyField(Model, through="MissingM2MModel")
class Person(models.Model):
name = models.CharField(max_length=5)
class Group(models.Model):
name = models.CharField(max_length=5)
primary = models.ManyToManyField(Person, through="Membership", related_name="primary")
secondary = models.ManyToManyField(Person, through="Membership", related_name="secondary")
tertiary = models.ManyToManyField(Person, through="RelationshipDoubleFK", related_name="tertiary")
class GroupTwo(models.Model):
name = models.CharField(max_length=5)
primary = models.ManyToManyField(Person, through="Membership")
secondary = models.ManyToManyField(Group, through="MembershipMissingFK")
class Membership(models.Model):
person = models.ForeignKey(Person)
group = models.ForeignKey(Group)
not_default_or_null = models.CharField(max_length=5)
class MembershipMissingFK(models.Model):
person = models.ForeignKey(Person)
class PersonSelfRefM2M(models.Model):
name = models.CharField(max_length=5)
friends = models.ManyToManyField('self', through="Relationship")
too_many_friends = models.ManyToManyField('self', through="RelationshipTripleFK")
class PersonSelfRefM2MExplicit(models.Model):
name = models.CharField(max_length=5)
friends = models.ManyToManyField('self', through="ExplicitRelationship", symmetrical=True)
class Relationship(models.Model):
first = models.ForeignKey(PersonSelfRefM2M, related_name="rel_from_set")
second = models.ForeignKey(PersonSelfRefM2M, related_name="rel_to_set")
date_added = models.DateTimeField()
class ExplicitRelationship(models.Model):
first = models.ForeignKey(PersonSelfRefM2MExplicit, related_name="rel_from_set")
second = models.ForeignKey(PersonSelfRefM2MExplicit, related_name="rel_to_set")
date_added = models.DateTimeField()
class RelationshipTripleFK(models.Model):
first = models.ForeignKey(PersonSelfRefM2M, related_name="rel_from_set_2")
second = models.ForeignKey(PersonSelfRefM2M, related_name="rel_to_set_2")
third = models.ForeignKey(PersonSelfRefM2M, related_name="too_many_by_far")
date_added = models.DateTimeField()
class RelationshipDoubleFK(models.Model):
first = models.ForeignKey(Person, related_name="first_related_name")
second = models.ForeignKey(Person, related_name="second_related_name")
third = models.ForeignKey(Group, related_name="rel_to_set")
date_added = models.DateTimeField()
model_errors = """invalid_models.fielderrors: "charfield": CharFields require a "max_length" attribute.
invalid_models.fielderrors: "decimalfield": DecimalFields require a "decimal_places" attribute.
......@@ -195,4 +252,12 @@ invalid_models.selfclashm2m: Reverse query name for m2m field 'm2m_3' clashes wi
invalid_models.selfclashm2m: Reverse query name for m2m field 'm2m_4' clashes with field 'SelfClashM2M.selfclashm2m'. Add a related_name argument to the definition for 'm2m_4'.
invalid_models.missingrelations: 'rel2' has m2m relation with model Rel2, which has not been installed
invalid_models.missingrelations: 'rel1' has relation with model Rel1, which has not been installed
invalid_models.grouptwo: 'primary' has a manually-defined m2m relation through model Membership, which does not have foreign keys to Person and GroupTwo
invalid_models.grouptwo: 'secondary' has a manually-defined m2m relation through model MembershipMissingFK, which does not have foreign keys to Group and GroupTwo
invalid_models.missingmanualm2mmodel: 'missing_m2m' specifies an m2m relation through model MissingM2MModel, which has not been installed
invalid_models.group: The model Group has two manually-defined m2m relations through the model Membership, which is not permitted. Please consider using an extra field on your intermediary model instead.
invalid_models.group: Intermediary model RelationshipDoubleFK has more than one foreign key to Person, which is ambiguous and is not permitted.
invalid_models.personselfrefm2m: Many-to-many fields with intermediate tables cannot be symmetrical.
invalid_models.personselfrefm2m: Intermediary model RelationshipTripleFK has more than two foreign keys to PersonSelfRefM2M, which is ambiguous and is not permitted.
invalid_models.personselfrefm2mexplicit: Many-to-many fields with intermediate tables cannot be symmetrical.
"""
This diff is collapsed.
from django.db import models
from datetime import datetime
from django.contrib.auth.models import User
# Forward declared intermediate model
class Membership(models.Model):
person = models.ForeignKey('Person')
group = models.ForeignKey('Group')
date_joined = models.DateTimeField(default=datetime.now)
def __unicode__(self):
return "%s is a member of %s" % (self.person.name, self.group.name)
class UserMembership(models.Model):
user = models.ForeignKey(User)
group = models.ForeignKey('Group')
date_joined = models.DateTimeField(default=datetime.now)
def __unicode__(self):
return "%s is a user and member of %s" % (self.user.username, self.group.name)
class Person(models.Model):
name = models.CharField(max_length=128)
def __unicode__(self):
return self.name
class Group(models.Model):
name = models.CharField(max_length=128)
# Membership object defined as a class
members = models.ManyToManyField(Person, through=Membership)
user_members = models.ManyToManyField(User, through='UserMembership')
def __unicode__(self):
return self.name
__test__ = {'API_TESTS':"""
# Create some dummy data
>>> bob = Person.objects.create(name='Bob')
>>> jim = Person.objects.create(name='Jim')
>>> rock = Group.objects.create(name='Rock')
>>> roll = Group.objects.create(name='Roll')
>>> frank = User.objects.create_user('frank','frank@example.com','password')
>>> jane = User.objects.create_user('jane','jane@example.com','password')
# Now test that the forward declared Membership works
>>> Membership.objects.create(person=bob, group=rock)
<Membership: Bob is a member of Rock>
>>> Membership.objects.create(person=bob, group=roll)
<Membership: Bob is a member of Roll>
>>> Membership.objects.create(person=jim, group=rock)
<Membership: Jim is a member of Rock>
>>> bob.group_set.all()
[<Group: Rock>, <Group: Roll>]
>>> roll.members.all()
[<Person: Bob>]
# Error messages use the model name, not repr of the class name
>>> bob.group_set = []
Traceback (most recent call last):
...
AttributeError: Cannot set values on a ManyToManyField which specifies an intermediary model. Use Membership's Manager instead.
>>> roll.members = []
Traceback (most recent call last):
...
AttributeError: Cannot set values on a ManyToManyField which specifies an intermediary model. Use Membership's Manager instead.
>>> rock.members.create(name='Anne')
Traceback (most recent call last):
...
AttributeError: Cannot use create() on a ManyToManyField which specifies an intermediary model. Use Membership's Manager instead.
>>> bob.group_set.create(name='Funk')
Traceback (most recent call last):
...
AttributeError: Cannot use create() on a ManyToManyField which specifies an intermediary model. Use Membership's Manager instead.
# Now test that the intermediate with a relationship outside
# the current app (i.e., UserMembership) workds
>>> UserMembership.objects.create(user=frank, group=rock)
<UserMembership: frank is a user and member of Rock>
>>> UserMembership.objects.create(user=frank, group=roll)
<UserMembership: frank is a user and member of Roll>
>>> UserMembership.objects.create(user=jane, group=rock)
<UserMembership: jane is a user and member of Rock>
>>> frank.group_set.all()
[<Group: Rock>, <Group: Roll>]
>>> roll.user_members.all()
[<User: frank>]
"""}
from django.db import models
from datetime import datetime
from django.contrib.auth.models import User
# Forward declared intermediate model
class Membership(models.Model):
person = models.ForeignKey('Person')
group = models.ForeignKey('Group')
date_joined = models.DateTimeField(default=datetime.now)
def __unicode__(self):
return "%s is a member of %s" % (self.person.name, self.group.name)
class UserMembership(models.Model):
user = models.ForeignKey(User)
group = models.ForeignKey('Group')
date_joined = models.DateTimeField(default=datetime.now)
def __unicode__(self):
return "%s is a user and member of %s" % (self.user.username, self.group.name)
class Person(models.Model):
name = models.CharField(max_length=128)
def __unicode__(self):
return self.name
class Group(models.Model):
name = models.CharField(max_length=128)
# Membership object defined as a class
members = models.ManyToManyField(Person, through=Membership)
user_members = models.ManyToManyField(User, through='UserMembership')
def __unicode__(self):
return self.name
__test__ = {'API_TESTS':"""
# Create some dummy data
>>> bob = Person.objects.create(name='Bob')
>>> jim = Person.objects.create(name='Jim')
>>> rock = Group.objects.create(name='Rock')
>>> roll = Group.objects.create(name='Roll')
>>> frank = User.objects.create_user('frank','frank@example.com','password')
>>> jane = User.objects.create_user('jane','jane@example.com','password')
# Now test that the forward declared Membership works
>>> Membership.objects.create(person=bob, group=rock)
<Membership: Bob is a member of Rock>
>>> Membership.objects.create(person=bob, group=roll)
<Membership: Bob is a member of Roll>
>>> Membership.objects.create(person=jim, group=rock)
<Membership: Jim is a member of Rock>
>>> bob.group_set.all()
[<Group: Rock>, <Group: Roll>]
>>> roll.members.all()
[<Person: Bob>]
# Error messages use the model name, not repr of the class name
>>> bob.group_set = []
Traceback (most recent call last):
...
AttributeError: Cannot set values on a ManyToManyField which specifies an intermediary model. Use Membership's Manager instead.
>>> roll.members = []
Traceback (most recent call last):
...
AttributeError: Cannot set values on a ManyToManyField which specifies an intermediary model. Use Membership's Manager instead.
>>> rock.members.create(name='Anne')
Traceback (most recent call last):
...
AttributeError: Cannot use create() on a ManyToManyField which specifies an intermediary model. Use Membership's Manager instead.
>>> bob.group_set.create(name='Funk')
Traceback (most recent call last):
...
AttributeError: Cannot use create() on a ManyToManyField which specifies an intermediary model. Use Membership's Manager instead.
# Now test that the intermediate with a relationship outside
# the current app (i.e., UserMembership) workds
>>> UserMembership.objects.create(user=frank, group=rock)
<UserMembership: frank is a user and member of Rock>
>>> UserMembership.objects.create(user=frank, group=roll)
<UserMembership: frank is a user and member of Roll>
>>> UserMembership.objects.create(user=jane, group=rock)
<UserMembership: jane is a user and member of Rock>
>>> frank.group_set.all()
[<Group: Rock>, <Group: Roll>]
>>> roll.user_members.all()
[<User: frank>]
"""}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment