Ticket #6095: 6095-beta-06.diff

File 6095-beta-06.diff, 27.5 KB (added by floguy, 7 years ago)

Added/reworded lots of the comments to the m2m_manual doctests (maybe these tests need a rename, hmmm), and fixed some issues with the .diff that prevented parts from showing up last time.

  • AUTHORS

    diff --git a/AUTHORS b/AUTHORS
    index be18d21..49a5b31 100644
    a b answer newbie questions, and generally made Django that much better: 
    133133    Afonso Fernández Nogueira <fonzzo.django@gmail.com>
    134134    Matthew Flanagan <http://wadofstuff.blogspot.com>
    135135    Eric Floehr <eric@intellovations.com>
     136    Eric Florenzano <floguy@gmail.com>
    136137    Vincent Foley <vfoleybourgon@yahoo.ca>
    137138    Rudolph Froger <rfroger@estrate.nl>
    138139    Jorge Gajon <gajon@gajon.org>
  • django/core/management/sql.py

    diff --git a/django/core/management/sql.py b/django/core/management/sql.py
    index 15bffce..5430dea 100644
    a b def many_to_many_sql_for_model(model, style): 
    352352    qn = connection.ops.quote_name
    353353    inline_references = connection.features.inline_fk_references
    354354    for f in opts.many_to_many:
    355         if not isinstance(f.rel, generic.GenericRel):
     355        if not isinstance(f.rel, generic.GenericRel) and f.creates_table:
    356356            tablespace = f.db_tablespace or opts.db_tablespace
    357357            if tablespace and connection.features.supports_tablespaces and connection.features.autoindexes_primary_keys:
    358358                tablespace_sql = ' ' + connection.ops.tablespace_sql(tablespace, inline=True)
  • django/core/management/validation.py

    diff --git a/django/core/management/validation.py b/django/core/management/validation.py
    index bc9faae..a84cf35 100644
    a b def get_validation_errors(outfile, app=None): 
    104104                        if r.get_accessor_name() == rel_query_name:
    105105                            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))
    106106
     107        seen_intermediary_signatures = []
     108
    107109        for i, f in enumerate(opts.many_to_many):
    108110            # Check to see if the related m2m field will clash with any
    109111            # existing fields, m2m fields, m2m related objects or related objects
    def get_validation_errors(outfile, app=None): 
    113115                # so skip the next section
    114116                if isinstance(f.rel.to, (str, unicode)):
    115117                    continue
     118            if hasattr(f.rel, 'through') and f.rel.through != None:
     119                intermediary_model = None
     120                for model in models.get_models():
     121                    if model._meta.module_name == f.rel.through.lower():
     122                        intermediary_model = model
     123                if intermediary_model == None:
     124                    e.add(opts, "%s has a manually-defined m2m relationship through a model (%s) which does not exist." % (f.name, f.rel.through))
     125                else:
     126                    signature = (f.rel.to, cls, intermediary_model)
     127                    if signature in seen_intermediary_signatures:
     128                        e.add(opts, "%s has two manually-defined m2m relationships through the same model (%s), which is not possible.  Please use a field on your intermediary model instead." % (cls._meta.object_name, intermediary_model._meta.object_name))
     129                    else:
     130                        seen_intermediary_signatures.append(signature)
     131                    seen_related_fk, seen_this_fk = False, False
     132                    for field in intermediary_model._meta.fields:
     133                        if field.rel:
     134                            if field.rel.to == f.rel.to:
     135                                seen_related_fk = True
     136                            elif field.rel.to == cls:
     137                                seen_this_fk = True
     138                    if not seen_related_fk or not seen_this_fk:
     139                        e.add(opts, "%s has a manually-defined m2m relationship through a 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))
    116140
    117141            rel_opts = f.rel.to._meta
    118142            rel_name = RelatedObject(f.rel.to, cls, f).get_accessor_name()
  • django/db/models/fields/related.py

    diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py
    index 7d28ba1..9da7073 100644
    a b from django.core import validators 
    1010from django import oldforms
    1111from django import newforms as forms
    1212from django.dispatch import dispatcher
     13from new import instancemethod
    1314
    1415try:
    1516    set
    class ForeignRelatedObjectsDescriptor(object): 
    262263            manager.clear()
    263264        manager.add(*value)
    264265
    265 def create_many_related_manager(superclass):
     266def create_many_related_manager(superclass, through=False):
    266267    """Creates a manager that subclasses 'superclass' (which is a Manager)
    267268    and adds behavior for many-to-many related objects."""
    268269    class ManyRelatedManager(superclass):
    269270        def __init__(self, model=None, core_filters=None, instance=None, symmetrical=None,
    270                 join_table=None, source_col_name=None, target_col_name=None):
     271                join_table=None, source_col_name=None, target_col_name=None,
     272                through=None):
    271273            super(ManyRelatedManager, self).__init__()
    272274            self.core_filters = core_filters
    273275            self.model = model
    def create_many_related_manager(superclass): 
    276278            self.join_table = join_table
    277279            self.source_col_name = source_col_name
    278280            self.target_col_name = target_col_name
     281            self.through = through
    279282            self._pk_val = self.instance._get_pk_val()
    280283            if self._pk_val is None:
    281284                raise ValueError("%r instance needs to have a primary key value before a many-to-many relationship can be used." % model)
    def create_many_related_manager(superclass): 
    283286        def get_query_set(self):
    284287            return superclass.get_query_set(self).filter(**(self.core_filters))
    285288
    286         def add(self, *objs):
    287             self._add_items(self.source_col_name, self.target_col_name, *objs)
    288 
    289             # If this is a symmetrical m2m relation to self, add the mirror entry in the m2m table
    290             if self.symmetrical:
    291                 self._add_items(self.target_col_name, self.source_col_name, *objs)
    292         add.alters_data = True
    293 
    294         def remove(self, *objs):
    295             self._remove_items(self.source_col_name, self.target_col_name, *objs)
    296 
    297             # If this is a symmetrical m2m relation to self, remove the mirror entry in the m2m table
    298             if self.symmetrical:
    299                 self._remove_items(self.target_col_name, self.source_col_name, *objs)
    300         remove.alters_data = True
    301 
    302289        def clear(self):
    303290            self._clear_items(self.source_col_name)
    304291
    def create_many_related_manager(superclass): 
    375362                [self._pk_val])
    376363            transaction.commit_unless_managed()
    377364
     365    def add(self, *objs):
     366        self._add_items(self.source_col_name, self.target_col_name, *objs)
     367        # If this is a symmetrical m2m relation to self, add the mirror entry in the m2m table
     368        if self.symmetrical:
     369            self._add_items(self.target_col_name, self.source_col_name, *objs)
     370    add.alters_data = True
     371
     372    def remove(self, *objs):
     373        self._remove_items(self.source_col_name, self.target_col_name, *objs)
     374        # If this is a symmetrical m2m relation to self, remove the mirror entry in the m2m table
     375        if self.symmetrical:
     376            self._remove_items(self.target_col_name, self.source_col_name, *objs)
     377    remove.alters_data = True
     378
     379    if not through:
     380        ManyRelatedManager.add = instancemethod(add, None, ManyRelatedManager)
     381        ManyRelatedManager.remove = instancemethod(remove, None, ManyRelatedManager)
     382
    378383    return ManyRelatedManager
    379384
    380385class ManyRelatedObjectsDescriptor(object):
    class ManyRelatedObjectsDescriptor(object): 
    395400        # model's default manager.
    396401        rel_model = self.related.model
    397402        superclass = rel_model._default_manager.__class__
    398         RelatedManager = create_many_related_manager(superclass)
     403        RelatedManager = create_many_related_manager(superclass, self.related.field.rel.through)
    399404
    400405        qn = connection.ops.quote_name
    401406        manager = RelatedManager(
    class ManyRelatedObjectsDescriptor(object): 
    405410            symmetrical=False,
    406411            join_table=qn(self.related.field.m2m_db_table()),
    407412            source_col_name=qn(self.related.field.m2m_reverse_name()),
    408             target_col_name=qn(self.related.field.m2m_column_name())
     413            target_col_name=qn(self.related.field.m2m_column_name()),
     414            through=self.related.field.rel.through
    409415        )
    410416
    411417        return manager
    class ManyRelatedObjectsDescriptor(object): 
    414420        if instance is None:
    415421            raise AttributeError, "Manager must be accessed via instance"
    416422
     423        through = getattr(self.related.field.rel, 'through', None)
     424        if through:
     425            raise AttributeError, "Cannot set values on a ManyToManyField which specifies a through model.  Use %s's Manager instead." % through
     426       
    417427        manager = self.__get__(instance)
    418428        manager.clear()
    419429        manager.add(*value)
    class ReverseManyRelatedObjectsDescriptor(object): 
    436446        # model's default manager.
    437447        rel_model=self.field.rel.to
    438448        superclass = rel_model._default_manager.__class__
    439         RelatedManager = create_many_related_manager(superclass)
     449        RelatedManager = create_many_related_manager(superclass, self.field.rel.through)
    440450
    441451        qn = connection.ops.quote_name
    442452        manager = RelatedManager(
    class ReverseManyRelatedObjectsDescriptor(object): 
    446456            symmetrical=(self.field.rel.symmetrical and instance.__class__ == rel_model),
    447457            join_table=qn(self.field.m2m_db_table()),
    448458            source_col_name=qn(self.field.m2m_column_name()),
    449             target_col_name=qn(self.field.m2m_reverse_name())
     459            target_col_name=qn(self.field.m2m_reverse_name()),
     460            through=self.field.rel.through
    450461        )
    451462
    452463        return manager
    class ReverseManyRelatedObjectsDescriptor(object): 
    455466        if instance is None:
    456467            raise AttributeError, "Manager must be accessed via instance"
    457468
     469        through = getattr(self.field.rel, 'through', None)
     470        if through:
     471            raise AttributeError, "Cannot set values on a ManyToManyField which specifies a through model.  Use %s's Manager instead." % through
     472
    458473        manager = self.__get__(instance)
    459474        manager.clear()
    460475        manager.add(*value)
    class ManyToManyField(RelatedField, Field): 
    648663            filter_interface=kwargs.pop('filter_interface', None),
    649664            limit_choices_to=kwargs.pop('limit_choices_to', None),
    650665            raw_id_admin=kwargs.pop('raw_id_admin', False),
    651             symmetrical=kwargs.pop('symmetrical', True))
     666            symmetrical=kwargs.pop('symmetrical', True),
     667            through=kwargs.pop('through', None))
    652668        self.db_table = kwargs.pop('db_table', None)
     669        if kwargs['rel'].through:
     670            self.creates_table = False
     671            assert not self.db_table, "Cannot specify a db_table if an intermediary model is used."
     672        else:
     673            self.creates_table = True
    653674        if kwargs["rel"].raw_id_admin:
    654675            kwargs.setdefault("validator_list", []).append(self.isValidIDList)
    655676        Field.__init__(self, **kwargs)
    class ManyToManyField(RelatedField, Field): 
    672693
    673694    def _get_m2m_db_table(self, opts):
    674695        "Function that can be curried to provide the m2m table name for this relation"
    675         if self.db_table:
     696        if self.rel.through != None:
     697            return get_model(opts.app_label, self.rel.through)._meta.db_table
     698        elif self.db_table:
    676699            return self.db_table
    677700        else:
    678701            return '%s_%s' % (opts.db_table, self.name)
    class ManyToManyField(RelatedField, Field): 
    680703    def _get_m2m_column_name(self, related):
    681704        "Function that can be curried to provide the source column name for the m2m table"
    682705        # If this is an m2m relation to self, avoid the inevitable name clash
    683         if related.model == related.parent_model:
     706        if self.rel.through != None:
     707            field = related.model._meta.get_related_object(self.rel.through).field
     708            attname, column = field.get_attname_column()
     709            return column
     710        elif related.model == related.parent_model:
    684711            return 'from_' + related.model._meta.object_name.lower() + '_id'
    685712        else:
    686713            return related.model._meta.object_name.lower() + '_id'
    class ManyToManyField(RelatedField, Field): 
    688715    def _get_m2m_reverse_name(self, related):
    689716        "Function that can be curried to provide the related column name for the m2m table"
    690717        # If this is an m2m relation to self, avoid the inevitable name clash
    691         if related.model == related.parent_model:
     718        if self.rel.through != None:
     719            field = related.parent_model._meta.get_related_object(self.rel.through).field
     720            attname, column = field.get_attname_column()
     721            return column
     722        elif related.model == related.parent_model:
    692723            return 'to_' + related.parent_model._meta.object_name.lower() + '_id'
    693724        else:
    694725            return related.parent_model._meta.object_name.lower() + '_id'
    class OneToOneRel(ManyToOneRel): 
    809840
    810841class ManyToManyRel(object):
    811842    def __init__(self, to, num_in_admin=0, related_name=None,
    812         filter_interface=None, limit_choices_to=None, raw_id_admin=False, symmetrical=True):
     843        filter_interface=None, limit_choices_to=None, raw_id_admin=False, symmetrical=True,
     844        through = None):
    813845        self.to = to
    814846        self.num_in_admin = num_in_admin
    815847        self.related_name = related_name
    class ManyToManyRel(object): 
    821853        self.raw_id_admin = raw_id_admin
    822854        self.symmetrical = symmetrical
    823855        self.multiple = True
     856        self.through = through
    824857
    825858        assert not (self.raw_id_admin and self.filter_interface), "ManyToManyRels may not use both raw_id_admin and filter_interface"
  • django/db/models/options.py

    diff --git a/django/db/models/options.py b/django/db/models/options.py
    index 37ace0a..f0af416 100644
    a b from django.conf import settings 
    22from django.db.models.related import RelatedObject
    33from django.db.models.fields.related import ManyToManyRel
    44from django.db.models.fields import AutoField, FieldDoesNotExist
    5 from django.db.models.loading import get_models, app_cache_ready
     5from django.db.models.loading import get_models, get_model, app_cache_ready
    66from django.db.models.query import orderlist2sql
    77from django.db.models import Manager
    88from django.utils.translation import activate, deactivate_all, get_language, string_concat
    class Options(object): 
    162162            follow = self.get_follow()
    163163        return [f for f in self.get_all_related_objects() if follow.get(f.name, None)]
    164164
     165    def get_related_object(self, from_model):
     166        "Gets the RelatedObject which links from from_model to this model."
     167        if isinstance(from_model, str):
     168            from_model = get_model(self.app_label, from_model)
     169        for related_object in self.get_all_related_objects():
     170            if related_object.model == from_model:
     171                return related_object
     172        return None
     173
    165174    def get_data_holders(self, follow=None):
    166175        if follow == None:
    167176            follow = self.get_follow()
  • tests/modeltests/invalid_models/models.py

    diff --git a/tests/modeltests/invalid_models/models.py b/tests/modeltests/invalid_models/models.py
    index 8a480a2..191950d 100644
    a b class Car(models.Model): 
    111111class MissingRelations(models.Model):
    112112    rel1 = models.ForeignKey("Rel1")
    113113    rel2 = models.ManyToManyField("Rel2")
     114   
     115class MissingManualM2MModel(models.Model):
     116    name = models.CharField(max_length=5)
     117    missing_m2m = models.ManyToManyField(Model, through="MissingM2MModel")
     118   
     119class Person(models.Model):
     120    name = models.CharField(max_length=5)
     121
     122class Group(models.Model):
     123    name = models.CharField(max_length=5)
     124    primary = models.ManyToManyField(Person, through="Membership", related_name="primary")
     125    secondary = models.ManyToManyField(Person, through="Membership", related_name="secondary")
     126
     127class GroupTwo(models.Model):
     128    name = models.CharField(max_length=5)
     129    primary = models.ManyToManyField(Person, through="Membership")
     130    secondary = models.ManyToManyField(Group, through="MembershipMissingFK")
     131
     132class Membership(models.Model):
     133    person = models.ForeignKey(Person)
     134    group = models.ForeignKey(Group)
     135    not_default_or_null = models.CharField(max_length=5)
     136
     137class MembershipMissingFK(models.Model):
     138    person = models.ForeignKey(Person)
    114139
    115140model_errors = """invalid_models.fielderrors: "charfield": CharFields require a "max_length" attribute.
    116141invalid_models.fielderrors: "decimalfield": DecimalFields require a "decimal_places" attribute.
    invalid_models.selfclashm2m: Reverse query name for m2m field 'm2m_3' clashes wi 
    197222invalid_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'.
    198223invalid_models.missingrelations: 'rel2' has m2m relation with model Rel2, which has not been installed
    199224invalid_models.missingrelations: 'rel1' has relation with model Rel1, which has not been installed
     225invalid_models.group: Group has two manually-defined m2m relationships through the same model (Membership), which is not possible.  Please use a field on your intermediary model instead.
     226invalid_models.missingmanualm2mmodel: missing_m2m has a manually-defined m2m relationship through a model (MissingM2MModel) which does not exist.
     227invalid_models.grouptwo: primary has a manually-defined m2m relationship through a model (Membership) which does not have foreign keys to Person and GroupTwo
     228invalid_models.grouptwo: secondary has a manually-defined m2m relationship through a model (MembershipMissingFK) which does not have foreign keys to Group and GroupTwo
    200229"""
  • new file tests/modeltests/m2m_manual/models.py

    diff --git a/tests/modeltests/m2m_manual/__init__.py b/tests/modeltests/m2m_manual/__init__.py
    new file mode 100644
    index 0000000..e69de29
    diff --git a/tests/modeltests/m2m_manual/models.py b/tests/modeltests/m2m_manual/models.py
    new file mode 100644
    index 0000000..089cf44
    - +  
     1from django.db import models
     2from datetime import datetime
     3
     4# M2M described on one of the models
     5class Person(models.Model):
     6    name = models.CharField(max_length=128)
     7
     8    def __unicode__(self):
     9        return self.name
     10
     11class Group(models.Model):
     12    name = models.CharField(max_length=128)
     13    members = models.ManyToManyField(Person, through='Membership')
     14    custom_members = models.ManyToManyField(Person, through='CustomMembership', related_name="custom")
     15    nodefaultsnonulls = models.ManyToManyField(Person, through='TestNoDefaultsOrNulls', related_name="testnodefaultsnonulls")
     16   
     17    def __unicode__(self):
     18        return self.name
     19
     20class Membership(models.Model):
     21    person = models.ForeignKey(Person)
     22    group = models.ForeignKey(Group)
     23    date_joined = models.DateTimeField(default=datetime.now)
     24    invite_reason = models.CharField(max_length=64, null=True)
     25   
     26    def __unicode__(self):
     27        return "%s is a member of %s" % (self.person.name, self.group.name)
     28
     29class CustomMembership(models.Model):
     30    person = models.ForeignKey(Person, db_column="custom_person_column", related_name="custom_person_related_name")
     31    group = models.ForeignKey(Group)
     32    weird_fk = models.ForeignKey(Membership, null=True)
     33    date_joined = models.DateTimeField(default=datetime.now)
     34   
     35    def __unicode__(self):
     36        return "%s is a member of %s" % (self.person.name, self.group.name)
     37   
     38    class Meta:
     39        db_table = "test_table"
     40
     41class TestNoDefaultsOrNulls(models.Model):
     42    person = models.ForeignKey(Person)
     43    group = models.ForeignKey(Group)
     44    nodefaultnonull = models.CharField(max_length=5)
     45
     46__test__ = {'API_TESTS':"""
     47>>> from datetime import datetime
     48
     49### Creation and Saving Tests ###
     50
     51>>> bob = Person.objects.create(name = 'Bob')
     52>>> jim = Person.objects.create(name = 'Jim')
     53>>> jane = Person.objects.create(name = 'Jane')
     54>>> rock = Group.objects.create(name = 'Rock')
     55>>> roll = Group.objects.create(name = 'Roll')
     56
     57# We start out by making sure that the Group 'rock' has no members.
     58>>> rock.members.all()
     59[]
     60
     61# To make Jim a member of Group Rock, simply create a Membership object.
     62>>> m1 = Membership.objects.create(person = jim, group = rock)
     63
     64# We can do the same for Jane and Rock.
     65>>> m2 = Membership.objects.create(person = jane, group = rock)
     66
     67# Let's check to make sure that it worked.  Jane and Jim should be members of Rock.
     68>>> rock.members.all()
     69[<Person: Jim>, <Person: Jane>]
     70
     71# Now we can add a bunch more Membership objects to test with.
     72>>> m3 = Membership.objects.create(person = bob, group = roll)
     73>>> m4 = Membership.objects.create(person = jim, group = roll)
     74>>> m5 = Membership.objects.create(person = jane, group = roll)
     75
     76# We can get Jim's Group membership as with any ForeignKey.
     77>>> jim.group_set.all()
     78[<Group: Rock>, <Group: Roll>]
     79
     80# Querying the intermediary model works like normal. 
     81# In this case we get Jane's membership to Rock.
     82>>> m = Membership.objects.get(person = jane, group = rock)
     83>>> m
     84<Membership: Jane is a member of Rock>
     85
     86# Now we set some date_joined dates for further testing.
     87>>> m2.invite_reason = "She was just awesome."
     88>>> m2.date_joined = datetime(2006, 1, 1)
     89>>> m2.save()
     90
     91>>> m5.date_joined = datetime(2004, 1, 1)
     92>>> m5.save()
     93
     94>>> m3.date_joined = datetime(2004, 1, 1)
     95>>> m3.save()
     96
     97# It's not only get that works.  Filter works like normal as well.
     98>>> Membership.objects.filter(person = jim)
     99[<Membership: Jim is a member of Rock>, <Membership: Jim is a member of Roll>]
     100
     101
     102### Forward Descriptors Tests ###
     103
     104# Due to complications with adding via an intermediary model, the add method is
     105# not provided.
     106>>> rock.members.add(bob)
     107Traceback (most recent call last):
     108...
     109AttributeError: 'ManyRelatedManager' object has no attribute 'add'
     110
     111# Remove has similar complications, and is not provided either.
     112>>> rock.members.remove(jim)
     113Traceback (most recent call last):
     114...
     115AttributeError: 'ManyRelatedManager' object has no attribute 'remove'
     116
     117# Here we back up the list of all members of Rock.
     118>>> backup = list(rock.members.all())
     119# ...and we verify that it has worked.
     120>>> backup
     121[<Person: Jim>, <Person: Jane>]
     122
     123# The clear function should still work.
     124>>> rock.members.clear()
     125# Now there will be no members of Rock.
     126>>> rock.members.all()
     127[]
     128
     129# Assignment should not work with models specifying a through model for many of
     130# the same reasons as adding.
     131>>> rock.members = backup
     132Traceback (most recent call last):
     133...
     134AttributeError: Cannot set values on a ManyToManyField which specifies a through model.  Use Membership's Manager instead.
     135
     136# Let's re-save those instances that we've cleared.
     137>>> m1.save()
     138>>> m2.save()
     139
     140# Verifying that those instances were re-saved successfully.
     141>>> rock.members.all()
     142[<Person: Jim>, <Person: Jane>]
     143
     144
     145### Reverse Descriptors Tests ###
     146
     147# Due to complications with adding via an intermediary model, the add method is
     148# not provided.
     149>>> bob.group_set.add(rock)
     150Traceback (most recent call last):
     151...
     152AttributeError: 'ManyRelatedManager' object has no attribute 'add'
     153
     154# Remove has similar complications, and is not provided either.
     155>>> jim.group_set.remove(rock)
     156Traceback (most recent call last):
     157...
     158AttributeError: 'ManyRelatedManager' object has no attribute 'remove'
     159
     160# Here we back up the list of all of Jim's groups.
     161>>> backup = list(jim.group_set.all())
     162>>> backup
     163[<Group: Rock>, <Group: Roll>]
     164
     165# The clear function should still work.
     166>>> jim.group_set.clear()
     167# Now Jim will be in no groups.
     168>>> jim.group_set.all()
     169[]
     170
     171# Assignment should not work with models specifying a through model for many of
     172# the same reasons as adding.
     173>>> jim.group_set = backup
     174Traceback (most recent call last):
     175...
     176AttributeError: Cannot set values on a ManyToManyField which specifies a through model.  Use Membership's Manager instead.
     177
     178# Let's re-save those instances that we've cleared.
     179>>> m1.save()
     180>>> m4.save()
     181
     182# Verifying that those instances were re-saved successfully.
     183>>> jim.group_set.all()
     184[<Group: Rock>, <Group: Roll>]
     185
     186### Custom Tests ###
     187
     188# Let's see if we can query through our second relationship.
     189>>> rock.custom_members.all()
     190[]
     191# We can query in the opposite direction as well.
     192>>> bob.custom.all()
     193[]
     194
     195# Let's create some membership objects in this custom relationship.
     196>>> cm1 = CustomMembership.objects.create(person = bob, group = rock)
     197>>> cm2 = CustomMembership.objects.create(person = jim, group = rock)
     198
     199# If we get the number of people in Rock, it should be both Bob and Jim.
     200>>> rock.custom_members.all()
     201[<Person: Bob>, <Person: Jim>]
     202
     203# Bob should only be in one custom group.
     204>>> bob.custom.all()
     205[<Group: Rock>]
     206
     207# Let's make sure our new descriptors don't conflict with the FK related_name.
     208>>> bob.custom_person_related_name.all()
     209[<CustomMembership: Bob is a member of Rock>]
     210
     211### QUERY TESTS ###
     212
     213# We can query for the related model by using its attribute name (members, in
     214# this case).
     215>>> Group.objects.filter(members__name='Bob')
     216[<Group: Roll>]
     217
     218# To query through the intermediary model, we specify its model name.
     219# In this case, membership.
     220>>> Group.objects.filter(membership__invite_reason = "She was just awesome.")
     221[<Group: Rock>]
     222
     223# If we want to query in the reverse direction by the related model, use its
     224# model name (group, in this case).
     225>>> Person.objects.filter(group__name="Rock")
     226[<Person: Jim>, <Person: Jane>]
     227
     228# If the m2m field has specified a related_name, using that will work.
     229>>> Person.objects.filter(custom__name="Rock")
     230[<Person: Bob>, <Person: Jim>]
     231
     232# To query through the intermediary model in the reverse direction, we again
     233# specify its model name (membership, in this case).
     234>>> Person.objects.filter(membership__invite_reason = "She was just awesome.")
     235[<Person: Jane>]
     236
     237# Let's see all of the groups that Jane joined after 1 Jan 2005:
     238>>> Group.objects.filter(membership__date_joined__gt = datetime(2005, 1, 1),
     239... membership__person = jane)
     240[<Group: Rock>]
     241
     242# Queries also work in the reverse direction: Now let's see all of the people
     243# that have joined Rock since 1 Jan 2005:
     244>>> Person.objects.filter(membership__date_joined__gt = datetime(2005, 1, 1),
     245... membership__group = rock)
     246[<Person: Jim>, <Person: Jane>]
     247
     248# Conceivably, queries through membership could return correct, but non-unique
     249# querysets.  To demonstrate this, we query for all people who have joined a
     250# group after 2004:
     251>>> Person.objects.filter(membership__date_joined__gt = datetime(2004, 1, 1))
     252[<Person: Jim>, <Person: Jim>, <Person: Jane>]
     253
     254# Jim showed up twice, because he joined two groups ('Rock', and 'Roll'):
     255>>> [(m.person.name, m.group.name) for m in
     256... Membership.objects.filter(date_joined__gt = datetime(2004, 1, 1))]
     257[(u'Jim', u'Rock'), (u'Jane', u'Rock'), (u'Jim', u'Roll')]
     258
     259# QuerySet's distinct() method can correct this problem.
     260>>> Person.objects.filter(membership__date_joined__gt = datetime(2004, 1, 1)).distinct()
     261[<Person: Jim>, <Person: Jane>]
     262"""}
     263 No newline at end of file
Back to Top