Friday, October 28, 2011

Re: Model Inheritance and ModelForms

On Fri, Oct 28, 2011 at 7:50 AM, Alex <alexcorn@gmail.com> wrote:
> I've been scouring Google and the Django documentation and I can't
> figure out how to do this. I'm working on an inventory management
> system for my shop. My inventory models.py similar to the following:
>
>    class ItemType( models.Model ):
>        def __unicode__( self ):
>            return "blah blah blah"
>
>        itemType = models.CharField( max_length = 32 )
>        isBook = models.BooleanField()
>
>    class InventoryItem( models.Model ):
>        def __unicode__( self ):
>            return "blah"
>
>        itemType = models.ForeignKey( ItemType )
>        description = models.CharField( max_length = 256 )
>
>    class InventoryBook( InventoryItem ):
>        def __unicode__( self ):
>            return "blah blah"
>
>        title = models.CharField( max_length = 64 )
>
> In my web app, I create a ModelForm based on InventoryItem and present
> that to the user. Upon submission, the POST data is used to create an
> instance of InventoryItem. I then check to see if
> inventoryItem.itemType.isBook() is True - if True, I want to cast
> inventoryItem to an InventoryBook type so I can set the extra fields
> and call save() so that it creates records in both tables in the MySQL
> database.
>
> I started trying to add a method to InventoryItem that would return an
> InventoryBook instance after being given the title string, but that
> doesn't work because Python doesn't have prototyping/forward
> declarations.
>
> Am I approaching this completely wrong, or am I just overlooking
> something simple? Any advice or links to relevant documentation would
> be *much* appreciated. Thanks!
>
> -Alex
>

If you have an InventoryItem which should be an InventoryBook, you
need to create the InventoryBook, not cast to it.

item = …
if item.itemType.isBook():
book = InventoryBook.objects.create(inventoryitem=item, title=…)

Inheritance like this in django isn't really like OOO inheritance,
InventoryBook just magically gains a OneToOneField back to
InventoryItem called inventoryitem.

Cheers

Tom

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment