Nick Craig-Wood <[EMAIL PROTECTED]> wrote: > > I'm adapting a legacy database for use with Django and I've come > across a problem I haven't been able to solve! > > The database has ForeignKey fields which are sometimes 0, meaning > there is no related row in the other table. If this database used > NULL instead of 0 then I could use ForeignKey(Other, null=True) and > all would work fine, but it doesn't and I can't change it. > > I've tried lots of different ways of making an adaptor to change the 0 > into a None when read from the database but I haven't made it work (or > even get called!) yet - can anyone give me a clue?
Just in case anyone is interested, after a great deal of reading the source code I managed to make it work. This is what I came up with from django.db import models from django.core.exceptions import ObjectDoesNotExist from django.db.models.fields.related import ReverseSingleRelatedObjectDescriptor class OptionalReverseSingleRelatedObjectDescriptor(ReverseSingleRelatedObjectDescriptor): """ Part of OptionalForeignKey implementation FIXME implement: When setting None is transated to 0 """ def __get__(self, instance, instance_type=None): try: value = super(OptionalReverseSingleRelatedObjectDescriptor, self).__get__(instance, instance_type) except ObjectDoesNotExist: value = None return value class OptionalForeignKey(models.ForeignKey): """ A ForeignKey, but when the related object isn't found the value is None """ def __init__(self, *args, **kwargs): kwargs['null'] = True kwargs['blank'] = True super(OptionalForeignKey, self).__init__(*args, **kwargs) def contribute_to_class(self, cls, name): super(OptionalForeignKey, self).contribute_to_class(cls, name) # Override this to get the Optional effect setattr(cls, self.name, OptionalReverseSingleRelatedObjectDescriptor(self)) -- Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~----------~----~----~----~------~----~------~--~---