Setting a preferred item of a many-to-one in Django

Posted by Mike DeSimone on Stack Overflow See other posts from Stack Overflow or by Mike DeSimone
Published on 2010-03-12T03:41:15Z Indexed on 2010/03/12 3:47 UTC
Read the original article Hit count: 214

Filed under:
|

I'm trying to create a Django model that handles the following:

  • An Item can have several Names.
  • One of the Names for an Item is its primary Name, i.e. the Name displayed given an Item.

(The model names were changed to protect the innocent.)

The models.py I've got looks like:

class Item(models.Model):
    primaryName = models.OneToOneField("Name", verbose_name="Primary Name", 
        related_name="_unused")
    def __unicode__(self):
        return self.primaryName.name

class Name(models.Model):
    item = models.ForeignKey(Item)
    name = models.CharField(max_length=32, unique=True)
    def __unicode__(self):
        return self.name

class Meta: ordering = [ 'name' ]

The admin.py looks like:

class NameInline(admin.TabularInline):
    model = Name

class ItemAdmin(admin.ModelAdmin):
    inlines = [ NameInline ]

admin.site.register(Item, ItemAdmin)

It looks like the database schema is working fine, but I'm having trouble with the admin, so I'm not sure of anything at this point. My main questions are:

  • How do I explain to the admin that primaryName needs to be one of the Names of the item being edited?
  • Is there a way to automatically set primaryName to the first Name found, if primaryName is not set, since I'm using inline admin for the names?

© Stack Overflow or respective owner

Related posts about django

Related posts about django-models