我有一堆不同的模型可以访问数据库中的不同表,并通过继承链接到彼此,如下所示:
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
类字段中的数据,以用于Fruit
和Apple
类中的查询。
如何按顺序运行每个父类中的所有查询,从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))
其中color
和name
来自" Food" ,如何访问apples
中的FoodGroup
媒体资源以及color
中的name
和Apples
字段?