I'm trying to create a Django model that handles the following:
- An
Itemcan have severalNames. - One of the
Names for anItemis its primaryName, i.e. theNamedisplayed given anItem.
(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
primaryNameneeds to be one of theNames of the item being edited? - Is there a way to automatically set
primaryNameto the firstNamefound, ifprimaryNameis not set, since I'm using inline admin for the names?
EDIT: Dang, I forgot this was still open. Anyway, I wound up redoing the model, replacing primaryName with just name (a CharField) in Item and renaming Name to Alias. This can't do what I wanted to (just search one table for a name), but I couldn't make the primaryName work if it didn't have null=True, since Item gets saved before any Names were created, meaning that any attempt to auto-assign a Name would see an empty QuerySet and fail.
The only way I could see it working was to have Name's save routine auto-set itself as its parent's primaryName if primaryName was NULL, which just didn't sit well with me.