Python 父模型中的链查询
我有一组不同的模型,它们访问数据库中的不同表,并通过继承相互链接,如下所示:Python 父模型中的链查询,python,django,django-models,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 un
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,并将其分配给一个变量
我可以使用
seed = Seed._meta.get_parent_list()[2].objects.get(name=name)
但是,我如何将所有查询一起调用呢
先谢谢你
编辑/添加:
在下面的评论中,Daniel Roseman建议使用ForeignKey而不是继承。因此,新设置如下所示:
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,
)
如果苹果课是
class Apples(models.Model):
@cached_property
def apples():
return Apples.objects.filter(Q(color__contains=color) | Q(name__contains=name))
如果
color
和name
来自“Food”类,我如何访问FoodGroup
中的apples
属性以及apples
中的color
和name
字段?,但您可以访问Seed
实例上父模型的字段。您还可以在查询中使用父字段a laSeed.objects.get(foo=“bar”)
,即使foo
是Fruit
表中的字段。为什么在这里使用继承?它似乎不是正确的工具;标准外键会更好。@DanielRoseman您有一个例子说明我如何在不同的表/模型中使用外键吗?仅仅使用ForeignKey会导致我得到一个未知列
food.apple_id`in'field list`错误。似乎需要在contenttype框架中使用GenericForeignKey,但文档中对它的结果有点不清楚。不,您不需要通用外键,您需要实际的外键。教程中提供了一些示例。