Weblog

Model syntax changed

By popular demand, I'm about to change Django's model syntax to use "fieldname = FieldClass" instead of "FieldClass('fieldname')". This has been a longstanding ticket.

This change is BACKWARDS-INCOMPATIBLE, so don't "svn update" your code until you've changed your models. Old model syntax will not work.

I apologize for the backwards-incompatibility, but this is still unofficial software. ;-) Once we reach 1.0 -- which is much closer now that the model syntax is changed -- we'll be very dedicated to backwards-compatibility.

I can't think of any other backwards-incompatible changes that we're planning before 1.0 (knock on wood). If this isn't the last one, though, it's at least the last major one.

Here's a quick example of the new syntax:

class Foo(meta.Model):
    first_name = meta.CharField("The person's first name", maxlength=30)
    last_name = meta.CharField(maxlength=30)
    bar = meta.ForeignKey(Bar)
    sites = meta.ManyToManyField(Sites)
    class META:
        ordering = ('-bar',)
        admin = meta.Admin(
            fields = (
                (None, {'fields': ('first_name', 'last_name', 'bar', 'sites')}),
            ),
        )

    def __repr__(self):
        return self.first_name

Note that all non-field metadata goes in an inner class called "META".

Also note that ForeignKeys, ManyToManyFields and OneToOneFields are now required to have an explicit name (in the example, that's "bar" and "sites"). Before, field names for FK/MTM/OTO fields were optional (as a shortcut), and that caused people confusion -- they didn't know how to refer to fields within "admin.fields". Now it's explicit.

This change should be quite stable. I've been testing it for the past two days in our production setting at World Online. Thanks to that, I was able to iron out bugs as they came up. Also, I've updated every one of the model unit tests (and, hence, the model examples) to use the new syntax, and all tests pass.

Here's what you need to know to change your models:

Please send a note to the django-users mailing list or stop by IRC if you have any problems.

I've gone through the documentation and attempted to update it to use the new syntax. But I had to have missed something. If you're up for it, please take a look through our docs and let us know, by filing a ticket, if you find any bugs.

Finally, I just want to publicly thank mmarshall, rmunn, garthk, hugo, manuzhai and all the other great people who have contributed patches, ideas and passionate discussion to this change. This is the first really big community-driven improvement to Django, and it's been awesome to see it come to fruition. Thanks, guys!

Posted by Adrian Holovaty on August 25, 2005