On Sunday 13 February 2011 18:18:39 BW wrote: > I know you can override the save() method in a model, but is it > possible to do it when you try to get a row or rows from a db? I have > data like this '\xFF\x00\x00\x00\xFE'... that I need to store in a > MySQL db. > > When I was trying to save it I was getting an error. Now I override > the __save__ method and encode the data right before it's saved. This > works out fine, it's just that now I need to always code in the > decode('string-escape') every time I need to access the data. Is it > possible to override a method so when I use the A.objects.get / > filter / all methods it will automatically decode for me. Can I just > override a method like __get__ / __filter__ and just call the > superclass? I don't want to go down this road only to discover in a > couple of months that it's breaking something on the back end. > > (How I'm doing it now ) > class A(model): > encoded_data = models.TextField(max_length=4000) > > def __save__(self): > encoded_data = self.encoded_data.encode('string-escape') > super(A, self).save(*args, **kwargs) > > data = '\xFF\x00\x00\x00\xFE' #-- similar to this > aObject = A() > aObject.encoded_data = data > aObject.save() > > > anotherObject = A.objects.get(id=1) > decoded_data = anotherObject.encoded_data > decoded_data = decoded.data.decode('string-escape')
Why not make your own custom model field that does decoding/encoding as needed. No more hacking into save/get procedures. See <http://docs.djangoproject.com/en/1.2/howto/custom-model-fields/> for more information. -- Jani Tiainen -- 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 django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.