有效使用多表继承(一对一关系)

时间:2017-02-13 18:19:14

标签: django inheritance model multi-table-inheritance

我需要几个以一对一的关系从基类继承的模型。与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

甚至不确定如何转换为模板,但这段代码看起来非常错误且效率低下。

作为一种逃避,我猜你可以在一个地方做出一个选择字段来跟踪哪个子模型是相关的,但这相当于危险的非规范化。

我是否以某种方式过度思考这个?你是怎么做到的?

1 个答案:

答案 0 :(得分:1)

可能是简单的事情:

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 %}