tag (models)

archive

change an existing model, auth_user.username, max_length in django Jul
06
1
2

So lets say I had a model an an app that I didn't create that I wanted to change. Well, I would like to avoid going to that app and adjusting the code on the fly. Instead I would rather make the change in my custom application in order to keep the integrity of the code strong.

In my personal case I typically need to increase the max_length of the username in the django.contrib.auth package. You can perform the change by using the class_prepared signal:

# models.py
from django.db.models.signals import class_prepared

def longer_username(sender, *args, **kwargs):
    # you can't just do `if sender == django.contrib.auth.models.User`
    # because you have to import the model
    if sender.__name__ == 'User' and sender.__model__ == 'django.contrib.auth.models.User':
        sender._meta.get_field('username').max_length = 100

class_prepared.connect(longer_username)

You might need to change any help_text and forms.

This code will not update the underlying database. In order to make the update in the database I add a South schema migration.

import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models


class Migration(SchemaMigration):
    def fowards(self, orm):
        db.alter_column('auth_user', 'username', models.CharField(max_length=100))

    def backwards(self, orm):
        db.alter_column('auth_user', 'username', models.CharField(max_length=35))

# copy the rest of the file from the previous migration
# update the value for auth.user / username / maxlength

I don't think I need to say this, but this is hackish and should be used with great caution.

comments

django singleton Mar
17
1
0

Sometimes I have a django model that I want to behave like a singleton where there has to be one, and only one row present in the table at all times. I accomplish this by overriding the model's save() and delete() methods.

class Singleton(models.Model):
    # put model fields here

    def save(self):
        self.id=1
        super(Singleton, self).save()

    def delete(self):
        pass

comments