On Fri, 2009-08-07 at 01:24 -0700, Thierry wrote: > Hi, > > I have a model roughly defined as such (FK fields do not appear for > simplicity): > > class FieldChange(models.Model): > old_value = models.CharField(max_length=50) > new_value = models.CharField(max_length=50) > > Using SQLite, the table definition roughly translates to: > > CREATE TABLE "fieldchange" ( > "id" integer NOT NULL PRIMARY KEY, > "old_value" varchar(50) NOT NULL, > "new_value" varchar(50) NOT NULL, > ) > > However, it seems that the "max_length" condition is not respected, > neither at Django level (when saving)
Django does not currently do model-level validation. > nor at database level: SQLite respects SQL syntax, in that it accepts it without error, but it's internal storage format doesn't enforce that. You can put a string into a numeric field in SQLite and it won't complain. That's part of the reason for its code simplicity: you have to behave nicely when giving it data, because it isn't standing in the living room with a big stick enforcing much. > For instance, I managed to create a model instance with fields longer > than 50 characters and save it. > Worse, I managed to retrieve that instance with fields unchanged, i.e > their size still exceeding 50 characters (in a separate "django shell" > session). > > I expected the operation to fail at validation or DB backend level, or > at least that the fields would be truncated to comply with condition > "max_length=50". The latter behaviour would be very bad, since it would quietly lose data (the fact that MySQL does it and only raises a warning and not an error is, in my book, a design bug in MySQL). > Is there some kind of bad magic here? Or only related > to SQLite? No and yes, in that order. > Now what had me spot the error is that I wanted to manually truncate > 'old_value' and 'new_value' fields when data exceeds the 50 characters > limit (adding trailing '...' characters when necessary). Where is the > best location to do that? The model 'save()' method, I suppose? Yes. That's the ideal place for any cleanups of this variety. Honza Kral is working on model validation as part of his Django summer of code project and that contains normalisation passes as well, so this will be something that will be easier in a future version of Django (1.2, all things going well). For now, the save() method is an ideal place for any automatic translations. Regards, Malcolm --~--~---------~--~----~------------~-------~--~----~ 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 -~----------~----~----~----~------~----~------~--~---