toofishes.net

Django Proxy Models

With the Django 1.1 release, a new feature called proxy models was introduced. I didn’t discover this until today when I was giving my blog code a refresher to work with 1.1, but it ends up being the exact solution I needed for implementing a new admin action to delete spam comments and ban their IP addresses in one fell swoop.

So what are these proxy models? Normally when subclassing an existing Django model, the subclass will consist of a pointer to the parent class, and then any additional fields you may add to the class. What I really needed was a look-through class- I didn’t want to add any additional fields to the Comment model; I simply wanted to modify the admin to add a new action. My entire “new” model ended up like this (mycomments/models.py):

class MyComment(Comment):
    class Meta:
        proxy = True
        verbose_name = "Comment"

This allowed MyComment and Comment to more or less be interchanged. All of the existing comments in the database django_comments table just worked; no data migration was needed. More importantly, it allowed me to wire up a new ModelAdmin for the comments class where I could add a new action (mycomments/admin.py):

class MyCommentsAdmin(CommentsAdmin):
    actions = ['delete_and_ban']

    def delete_and_ban(self, request, queryset):
        pass

    delete_and_ban.short_description = "Delete and ban selected IP addresses"

admin.site.register(MyComment, MyCommentsAdmin)

The only additional step was to keep the default comments admin site from registering, this was accomplished by simply overriding the get_model() method for my custom comments application (mycomments/__init__.py):

def get_model():
    return MyComment

Tags

See Also