Ticket #6095: 6095-alpha-01.diff

File 6095-alpha-01.diff, 9.6 KB (added by floguy, 17 years ago)

Rudimentary patch to get the base functionality working. Tests were first, then implementation.

  • django/db/models/fields/related.py

     
    11from django.db import connection, transaction
    2 from django.db.models import signals, get_model
     2from django.db.models import signals, get_model, get_models
    33from django.db.models.fields import AutoField, Field, IntegerField, PositiveIntegerField, PositiveSmallIntegerField, get_ul_class
    44from django.db.models.related import RelatedObject
    55from django.utils.text import capfirst
    66from django.utils.translation import ugettext_lazy, string_concat, ungettext, ugettext as _
    7 from django.utils.functional import curry
     7from django.utils.functional import curry, memoize
    88from django.utils.encoding import smart_unicode
    99from django.core import validators
    1010from django import oldforms
     
    2323
    2424pending_lookups = {}
    2525
     26memoized_fk_field_reversals = {}
     27
     28model_db_table_cache = {}
     29
    2630def add_lookup(rel_cls, field):
    2731    name = field.rel.to
    2832    module = rel_cls.__module__
     
    5458    except klass.DoesNotExist:
    5559        raise validators.ValidationError, _("Please enter a valid %s.") % f.verbose_name
    5660
     61def get_reverse_rel_field(from_model, to_model, related_name):
     62    key = (from_model._meta.app_label, from_model._meta.object_name,
     63            to_model._meta.app_label, to_model._meta.object_name,
     64            related_name)
     65    try:
     66        found_field = memoized_fk_field_reversals[key]
     67    except KeyError:
     68        found_field = None
     69        for field in from_model._meta.fields:
     70            if field.__class__ in (ForeignKey, OneToOneField, ManyToManyField):
     71                if field.rel.related_name == related_name:
     72                    if field.rel.to == to_model:
     73                        found_field = field
     74                        break
     75        memoized_fk_field_reversals[key] = found_field
     76    return found_field
     77
     78def get_model_for_db_table(db_table):
     79    for model in get_models():
     80        if model._meta.db_table == db_table:
     81            return model
     82    return None
     83get_model_for_db_table = memoize(get_model_for_db_table, model_db_table_cache, 1)
     84
    5785#HACK
    5886class RelatedField(object):
    5987    def contribute_to_class(self, cls, name):
     
    276304            self.join_table = join_table
    277305            self.source_col_name = source_col_name
    278306            self.target_col_name = target_col_name
     307            self.intermediary_model = get_model_for_db_table(self.join_table.replace('"',''))
    279308            self._pk_val = self.instance._get_pk_val()
    280309            if self._pk_val is None:
    281310                raise ValueError("%r instance needs to have a primary key value before a many-to-many relationship can be used." % model)
     
    340369
    341370                # Add the ones that aren't there already
    342371                for obj_id in (new_ids - existing_ids):
    343                     cursor.execute("INSERT INTO %s (%s, %s) VALUES (%%s, %%s)" % \
     372                    if self.intermediary_model == None:
     373                        cursor.execute("INSERT INTO %s (%s, %s) VALUES (%%s, %%s)" % \
    344374                        (self.join_table, source_col_name, target_col_name),
    345375                        [self._pk_val, obj_id])
     376                    else:
     377                        new_obj = self.intermediary_model()
     378                        setattr(new_obj, source_col_name.replace('"', ''), self._pk_val)
     379                        setattr(new_obj, target_col_name.replace('"', ''), obj_id)
     380                        new_obj.save()
    346381                transaction.commit_unless_managed()
    347382
    348383        def _remove_items(self, source_col_name, target_col_name, *objs):
     
    648683            filter_interface=kwargs.pop('filter_interface', None),
    649684            limit_choices_to=kwargs.pop('limit_choices_to', None),
    650685            raw_id_admin=kwargs.pop('raw_id_admin', False),
    651             symmetrical=kwargs.pop('symmetrical', True))
     686            symmetrical=kwargs.pop('symmetrical', True),
     687            through=kwargs.pop('through', None))
    652688        self.db_table = kwargs.pop('db_table', None)
    653689        if kwargs["rel"].raw_id_admin:
    654690            kwargs.setdefault("validator_list", []).append(self.isValidIDList)
     
    672708
    673709    def _get_m2m_db_table(self, opts):
    674710        "Function that can be curried to provide the m2m table name for this relation"
    675         if self.db_table:
     711        if self.rel.through != None:
     712            return get_model(opts.app_label, self.rel.through)._meta.db_table
     713        elif self.db_table:
    676714            return self.db_table
    677715        else:
    678716            return '%s_%s' % (opts.db_table, self.name)
     
    680718    def _get_m2m_column_name(self, related):
    681719        "Function that can be curried to provide the source column name for the m2m table"
    682720        # If this is an m2m relation to self, avoid the inevitable name clash
    683         if related.model == related.parent_model:
     721        if self.rel.through != None:
     722            through = get_model(related.opts.app_label, self.rel.through)
     723            field = get_reverse_rel_field(through, related.model, self.rel.related_name)
     724            attname, column = field.get_attname_column()
     725            return column
     726        elif related.model == related.parent_model:
    684727            return 'from_' + related.model._meta.object_name.lower() + '_id'
    685728        else:
    686729            return related.model._meta.object_name.lower() + '_id'
     
    688731    def _get_m2m_reverse_name(self, related):
    689732        "Function that can be curried to provide the related column name for the m2m table"
    690733        # If this is an m2m relation to self, avoid the inevitable name clash
    691         if related.model == related.parent_model:
     734        if self.rel.through != None:
     735            through = get_model(related.opts.app_label, self.rel.through)
     736            field = get_reverse_rel_field(through, related.parent_model, self.rel.related_name)
     737            attname, column = field.get_attname_column()
     738            return column
     739        elif related.model == related.parent_model:
    692740            return 'to_' + related.parent_model._meta.object_name.lower() + '_id'
    693741        else:
    694742            return related.parent_model._meta.object_name.lower() + '_id'
     
    809857
    810858class ManyToManyRel(object):
    811859    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):
     860        filter_interface=None, limit_choices_to=None, raw_id_admin=False, symmetrical=True,
     861        through = None):
    813862        self.to = to
    814863        self.num_in_admin = num_in_admin
    815864        self.related_name = related_name
     
    821870        self.raw_id_admin = raw_id_admin
    822871        self.symmetrical = symmetrical
    823872        self.multiple = True
     873        self.through = through
    824874
    825875        assert not (self.raw_id_admin and self.filter_interface), "ManyToManyRels may not use both raw_id_admin and filter_interface"
  • django/core/management/sql.py

     
    349349    qn = connection.ops.quote_name
    350350    inline_references = connection.features.inline_fk_references
    351351    for f in opts.many_to_many:
    352         if not isinstance(f.rel, generic.GenericRel):
     352        if not isinstance(f.rel, generic.GenericRel) and getattr(f.rel, 'through', None) == None:
    353353            tablespace = f.db_tablespace or opts.db_tablespace
    354354            if tablespace and connection.features.supports_tablespaces and connection.features.autoindexes_primary_keys:
    355355                tablespace_sql = ' ' + connection.ops.tablespace_sql(tablespace, inline=True)
  • tests/modeltests/m2m_manual/models.py

     
     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   
     15    def __unicode__(self):
     16        return self.name
     17
     18class Membership(models.Model):
     19    person = models.ForeignKey(Person)
     20    group = models.ForeignKey(Group)
     21    date_joined = models.DateTimeField(default=datetime.now)
     22   
     23    def __unicode__(self):
     24        return "%s is a member of %s" % (self.person.name, self.group.name)
     25
     26__test__ = {'API_TESTS':"""
     27>>> bob = Person(name = 'Bob')
     28>>> bob.save()
     29>>> jim = Person(name = 'Jim')
     30>>> jim.save()
     31>>> jane = Person(name = 'Jane')
     32>>> jane.save()
     33>>> rock = Group(name = 'Rock')
     34>>> rock.save()
     35>>> roll = Group(name = 'Roll')
     36>>> roll.save()
     37
     38>>> rock.members.add(jim, jane)
     39>>> rock.members.all()
     40[<Person: Jim>, <Person: Jane>]
     41
     42>>> roll.members.add(bob, jim)
     43>>> roll.members.all()
     44[<Person: Bob>, <Person: Jim>]
     45
     46>>> jane.group_set.all()
     47[<Group: Rock>]
     48
     49>>> jane.group_set.add(roll)
     50>>> jane.group_set.all()
     51[<Group: Rock>, <Group: Roll>]
     52
     53>>> jim.group_set.all()
     54[<Group: Rock>, <Group: Roll>]
     55
     56>>> Membership.objects.filter(person = jane, group = rock)
     57[<Membership: Jane is a member of Rock>]
     58
     59>>> Membership.objects.filter(person = jim)
     60[<Membership: Jim is a member of Rock>, <Membership: Jim is a member of Roll>]
     61"""}
     62 No newline at end of file
Back to Top