父模型

时间:2017-01-21 15:59:51

标签: python django django-models

我有一堆不同的模型可以访问数据库中的不同表,并通过继承链接到彼此,如下所示:

class Food(models.Model):
    # Some unique fields and properties

    # Meta
    class Meta:
        abstract = True # Inherited by two "food groups" with different tables


class FoodGroup(Food):
    # Some unique fields and properties

    # Meta
    class Meta:
        db_table = 'foodgroup'

class Fruit(FoodGroup):
    # Some unique fields and properties

    # Meta
    class Meta:
        db_table = 'fruit'


class Apple(Fruit):
    # Some unique fields and properties

    # Meta
    class Meta:
        db_table = 'apple'


class Seed(Apple):
    # This is a placeholder to collect all of the data
    # under a name that makes sense rather than just "Apple"

    # One unique field

    # Meta
    class Meta:
        managed = False # Doesn't have a table

我希望能够创建一个Seed类的实例,该实例具有各自表中的所有父类字段,并允许我只通过一个Seed对象访问它。问题是我需要来自Food类字段中的数据,以用于FruitApple类中的查询。

如何按顺序运行每个父类中的所有查询,从Food到Apple并将其分配给一个变量?

我可以使用

为一个特定的父类调用objects.get()
seed = Seed._meta.get_parent_list()[2].objects.get(name=name)

但是如何将所有查询一起调用?

提前谢谢。

编辑/加法:

在下面的评论中,Daniel Roseman建议使用ForeignKeys而不是继承。所以新设置将是这样的:

class Food(models.Model):
    # Some unique fields and properties
    name = models.CharField(max_length=100)
    color = models.CharField(max_length=16)

    # Meta
    class Meta:
        abstract = True # Inherited by two "food groups" with different tables

class FoodGroup(Food):
    apples = models.ForeignKey(
          'Apples',
          on_delete=models.CASCADE,
    )

如果Apples类是

class Apples(models.Model):
    @cached_property
    def apples():
        return Apples.objects.filter(Q(color__contains=color) | Q(name__contains=name))

其中colorname来自" Food" ,如何访问apples中的FoodGroup媒体资源以及color中的nameApples字段?

0 个答案:

没有答案
相关问题