0

I have this models:

from django.db import models

class Item(models.Model):
    # ...

    def __str__(self):
        return 'item'

class SubItemA(Item):
    # ...

    def __str__(self):
        return 'subitem_a'

class SubItemB(Item):
    # ...

    def __str__(self):
        return 'subitem_b'

And I want to call the __str__ method from each Item in Item.object.all() and return each subclass implementation, but it only return the superclass implementation.

Example:

for item in Item.object.all():
    print(item.__str__())

On my database I have two SubItemA and two SubItemB. Than it returns:

item
item
item
item

I would like to have some thing like this:

subitem_a
subitem_a
subitem_b
subitem_b

I am lost here.

Rhemzo
  • 73
  • 6
  • with this you will be stumbling upon more problems. A clean solution without reinventing a wheel is to use something like Django Polymorphic https://github.com/chrisglass/django_polymorphic – yedpodtrzitko Mar 31 '16 at 02:04
  • @yedpodtrzitko Thank you! It solved my problem like a charm! Please, write a answer so I can vote for it. – Rhemzo Mar 31 '16 at 13:56

2 Answers2

1

It's a bit involved. You might look at Django model subclassing: Get the subclass by querying the superclass for a full discussion.

Short answer, from that question:

def related_object(self, default_pointer_name='_ptr'):
    models = [A,B] #models
    object = None

    argument = '%s%s' %(self.__class__.__name__.lower(), default_pointer_name)
    query = { argument : self}

    for model in models:
        try:
            object = model.objects.get(**query)
        except model.DoesNotExist:
            pass
        else:
            return object

    if object == None:
        raise RelatedObjectException
    return object

# This is a method used by BaseMedium.
Community
  • 1
  • 1
Charles Merriam
  • 19,908
  • 6
  • 73
  • 83
0

With this you will be stumbling upon more problems. A clean solution without reinventing a wheel is to use something like Django Polymorphic

yedpodtrzitko
  • 9,035
  • 2
  • 40
  • 42