My Links
My Books
  • JBoss: A Developer's Notebook (Developers Notebook)
    JBoss: A Developer's Notebook (Developers Notebook)
    by Norman Richards, Sam Griffith
  • XDoclet in Action (In Action series)
    XDoclet in Action (In Action series)
    by Craig Walls, Norman Richards
  • JBoss 4.0 - The Official Guide
    JBoss 4.0 - The Official Guide
    by The JBoss Group
« No love for the monkey patch | Main | What exactly is open stack? »

An automatic primary key in django that works with inline model admin

I wanted to have a UUID primary field in a django model.  It isn't hard to create a CharField with a value that defaults to a UUID.   The django_extensions has a UUIDField is a nice all in one solution.  It works well as a primary key, except for a messy case with InlineModelAdmin which only allows non-editable primary keys if they are an AutoField.   

The workaround I found, after digging through the code a bit was to mimic the behavior of AutoField to trick InlineModelAdmin into doing the right thing.  I extended UUIDField like this:

After a bit more searching, I later found this was a known bug.  More interestingly, one of the commenters on the bug had considered the same solution and rejected it.  Take a look at the bug report for his reasoning, but the error condition he points out only occurs when the default value is None.  If the field has a default value, as is the case with this CharField-extended model, the potentially problematic logic doesn't kick in.  I haven't battle-tested the solution yet, but initial testing looks like it performs correctly. 

 

PrintView Printer Friendly Version

EmailEmail Article to Friend

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>