On May 4, 8:08 pm, Ole Laursen <[email protected]> wrote:
> The problem is that if I try to access foo.bar in any way, Django
> tries to lookup a bar with id 0 or -1 and throws an exception. My
> forms break, and the serializers break, making it hard to write test
> code. Does anyone know of an easy way to get around this?
After fighting with the descriptor API in Python, I managed to fix it
with the following piece of code. With it, you can say
noneify_field(Foo, 'bar') after the Foo model has been defined.
Haven't figured out to turn this idea into a field, however.
class NegativeAndNullToNoneOverrider(object):
"""Converts invalid ids (<= 0) to None before returning them to
Django."""
def __init__(self, cls, fieldname):
self.fieldname = fieldname
self.old_field = getattr(cls, fieldname)
def __get__(self, instance, instance_type=None):
if instance is None:
return self
v = getattr(instance, u"%s_id" % self.fieldname)
if v == None or v <= 0:
return None
else:
return self.old_field.__get__(instance, instance_type)
def __set__(self, instance, value):
# forward
self.old_field.__set__(instance, value)
def noneify_field(cls, fieldname):
"""Fixup field on class to make <= 0 mean None."""
setattr(cls, fieldname, NegativeAndNullToNoneOverrider(cls,
fieldname))
--
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.