简体   繁体   中英

How to call a superclass method and return the subclass implementation?

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM