简体   繁体   中英

Django model inheritance: access to child object from parent queryset

I'm have some models in my django project like these:

class Product(models.Model):
    name = models.Charfield(max_length=20)
    available = models.BooleanField(default=True)

class Tea(Product):
    image = models.ImageField(upload_to='products/tea')

class Coffee(Product):
    image = models.ImageField(upload_to='products/coffee')

In my ListView I'm have queryset which get me 5 available products:

Product.objects.filter(available=True)[:5]

In my template I would like render image from Tea/Coffee, how i can access from Product queryset to Tea/Coffee child object?

{% for product in products %}
    {{ product.????.image.url }}
{% endfor %}

I solve this problem with django-model-utils package.

Update parent model:

from model_utils.managers import InheritanceManager

class Product(models.Model):
    ...
    objects = InheritanceManager()

my queryset:

Product.objects.filter(available=True).select_subclasses()[:5]

and now i can use in template properties for submodels:

{% for product in products %}
    {{ product.image.url }}
{% endfor %}

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