Ok.
Here is my primitive implementation of 'ForeignKey' across databases.
It's still not clean for me - either should i use .using im the
pointed places, or django will use proper databases?
Also, ModelChoiceField when used in admin views - cannot show current
value somehow.
class AlienKey(models.Field):
"""
Link to a foreign model in another database.
Supposed to behave much like ForeignKey, except integrity
validation.
"""
__metaclass__ = models.SubfieldBase
def __init__(self, model, **kwargs):
self.ref_model = model
self.ref_field = model._meta.pk
kwargs['blank'] = True
kwargs['null'] = True
models.Field.__init__(self,**kwargs)
def get_internal_type(self):
return self.ref_field.get_internal_type()
def db_type(self,connection):
return
connection.creation.data_types[self.get_internal_type()] %
self.ref_field.__dict__
def to_python(self, val):
# val is either datasbe value or instance object
logging.debug(u"%s to_python %s"%(self,val))
if not val:
return None
elif isinstance(val,self.ref_model):
return val
else:
try:
return self.ref_model.objects.get(pk=val) # should i
put .using() here?
except:
return None
def get_prep_value(self, val):
logging.debug(u"%s prep %s"%(self,val))
if not val:
return None
elif isinstance(val,self.ref_model):
return getattr(val,self.ref_field.name)
else:
return None
def formfield(self, **kwargs):
defaults =
{
'form_class': forms.ModelChoiceField,
'queryset': self.ref_model.objects.all(), # should i
put .using() here?
'to_field_name': self.ref_field.name
}
defaults.update(kwargs)
return super(AlienKey, self).formfield(**defaults)
--
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to [email protected].
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.