Ticket #7800: gfk-from-option.diff

File gfk-from-option.diff, 2.3 KB (added by charmless, 16 years ago)

Initial sketch of 'from' option for GenericRelation

  • django/contrib/contenttypes/generic.py

     
    3838        # Connect myself as the descriptor for this field
    3939        setattr(cls, name, self)
    4040
     41        # Register my in the model's options
     42        # Is this a race waiting to happen?
     43        gfks = getattr(cls._meta, 'generic_foreign_keys', [])
     44        gfks.append(self)
     45        setattr(cls._meta, 'generic_foreign_keys', gfks)
     46       
     47
    4148    def instance_pre_init(self, signal, sender, args, kwargs, **_kwargs):
    4249        """
    4350        Handles initializing an object with the generic FK instaed of
     
    112119        self.creates_table = False
    113120
    114121        # Override content-type/object-id field names on the related class
    115         self.object_id_field_name = kwargs.pop("object_id_field", "object_id")
    116         self.content_type_field_name = kwargs.pop("content_type_field", "content_type")
     122        #self.object_id_field_name = kwargs.pop("object_id_field", "object_id")
     123        #self.content_type_field_name = kwargs.pop("content_type_field", "content_type")
     124        from_field = kwargs.pop('from', None)
     125        to_generic_fks = [field for field in getattr(to._meta, 'generic_foreign_keys', [])
     126                          if (field.__class__ == GenericForeignKey
     127                              and (from_field and (from_field == field.name) or True))]
     128        exc_args = {'named': from_field and (" named '%s'" % from_field) or "",
     129                    'to_model': to._meta.object_name,
     130                    'specify': from_field and "" or ": Specify one with the 'from' argument."}
     131        if len(to_generic_fks) == 0:
     132            raise Exception("No GenericForeignKey field%(named)s on '%(to_model)s' to relate to." % exc_args)
     133        elif len(to_generic_fks) > 1:
     134            raise Exception("Multiple GenericForeignKey fields%(named)s on '%(to_model)s' to relate to%(specify)s" % exc_args)
    117135
     136        gfk = to_generic_fks[0]
     137        self.object_id_field_name = gfk.fk_field
     138        self.content_type_field_name = gfk.ct_field
     139
     140
    118141        kwargs['blank'] = True
    119142        kwargs['editable'] = False
    120143        kwargs['serialize'] = False
Back to Top