简体   繁体   English

Django遍历模型子类

[英]Django iterate through model subclasses

I have following django models: 我有以下Django模型:

SALAMI_TYPES = (
    ('S', 'Spicy'),
    ('R', 'Regular')
)
CHEESES = (
    ('P', 'Parmesan'),
    ('C', 'Cheddar')
)
class Pizza(models.Model):
    size = models.IntegerField()
    class Meta:
        abstract = True

class Pepperoni(Pizza):
    salami = models.CharField(max_length=1, choices=SALAMI_TYPES)

class ExtraCheese(Pizza):
    cheese = models.CharField(max_length=1, choices=CHEESES)

And following questions: 以及以下问题:

  1. How to iterate thought different types of pizzas? 如何反复考虑不同类型的比萨饼? For example in menu template. 例如在菜单模板中。
  2. Where to store forms for each pizza type and how to connect them to a model. 每种披萨类型的存储位置以及如何将它们连接到模型。

Thanks. 谢谢。

You can do this by interrogating the python class hierarchy: 您可以通过查询python类层次结构来做到这一点:

How can I find all subclasses of a class given its name? 如何找到给定名称的类的所有子类?

In your case you would want to get all subclasses of 'Pizza', something like this: 在您的情况下,您希望获取“ Pizza”的所有子类,如下所示:

Pizza.__subclasses__()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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