Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

python - How to access child class object that inherits parent class?

I have parent class and child class, that inherits parent class. And that is okay, I can iterate with for loop. Now I want to access child class (example: 'product_type' So basically, I'm confused how we inherits stuff from child class inside the same loop...

views.py

from django.views import generic
from . models import Category
from django.shortcuts import render

class CategoryListView(generic.ListView):
    model = Category
    template_name = 'category_list.html'

models.py

from django.db import models
import uuid
    
class Category(models.Model):
    name = models.CharField(max_length=100, help_text='Category name')

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = 'Categories'
    
class Product(models.Model):
    product_name = models.CharField(max_length=255, help_text='Product name')
    # product_spec = models.TextField(max_length=5000, help_text='Product specs')
    product_type = models.ForeignKey('Category', on_delete=models.SET_NULL, null=True)

    def __str__(self):
        return self.product_name

category_list.html

{% extends 'base.html' %}


{% block body %}

{% for page in category_list %}
    <li>{{ page.name }}</li>
    <li>{{ page.product_name }} # <--------------- Now this is the point of 
                                                   #my problem, I want to get 
                                                   #product name from child 
                                                   #class 
                                                   #this returns empty <li>
{% endfor %}

{% endblock %}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

you can to this

{% extends 'base.html' %}


{% block body %}

{% for page in category_list %}
    <li>{{ page.name }}</li>
    <li>{{ page.product_set.first.product_name }} 
product name from child class, this returns empty <li>
{% endfor %}

{% endblock %}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...