有效使用Multi-table继承(一对一关系)

Effectively use Multi-table inheritance (one-to-one relationships)

我需要几个模型,它们以一对一的关系继承自基础 class。与 Django 示例保持一致:

from django.db import models

class Place(models.Model):
    name = models.CharField(max_length=50)

class Restaurant(Place):
    serves_hot_dogs = models.BooleanField(default=False)
    serves_pizza = models.BooleanField(default=False)

class Garage(Place):
    car_brands_serviced = Models.ManyToManyField(Brands)

class Boutique(Place):
    for = Models.ChoiceField(choices=( ("m", "men"), ("w", "women"), ("k","kids"))

# etc

现在,当我在模板(或视图函数)中迭代各种类型的 Places 时,如何有效区分它们?现在,我只看到这个解决方案(如果我想遍历地点,而不是单独的子模型):

for place in Place.objects.all():
    try:
        r = place.restaurant
        # Do restaurant stuff here
    except ObjectDoesNotExist:
        try:
            g = place.garage
            # Do garage stuff here
        except ObjectDoesNotExist:
            try:
                b = place.boutique
                # Do boutique stuff here
            except ObjectDoesNotExist:
                # Place is not specified

甚至不确定如何将其转化为模板,但这段代码似乎非常错误且效率低下。

作为一种逃避,我想你可以在 Place 中创建一个选择字段来跟踪哪个子模型是相关的,但这等同于危险的非规范化。

我是不是想多了?你是怎么做到的?

可以像这样简单吗:

models.py:

from django.db import models

class Place(models.Model):
    name = models.CharField(max_length=50)

class Restaurant(Place):
    serves_hot_dogs = models.BooleanField(default=False)
    serves_pizza = models.BooleanField(default=False)
    is_restaurant = True

class Garage(Place):
    car_brands_serviced = Models.ManyToManyField(Brands)
    is_garage = True

模板可以像这样工作 – template.html:

{% for place in places %}
 {% if place.is_restaurant %}
  <!-- Restaurant Stuff -->
 {% elif place.is_garage %}
  <!-- Garage Stuff -->
 {% endif %}
{% endfor %}