[英]Accessing child from parent
I have the models defined below: 我有以下定义的模型:
class PrimaryAsset(models.Model):
title = models.Charfield(max_length=200)
class Service(PrimaryAsset):
description = models.Charfield(max_length=200)
class Website(PrimaryAsset):
url = models.Charfield(max_length=200)
class AssetLinks(models.model):
high = models.ForeignKey(PrimaryAsset)
low = models.ForeignKey(PrimaryAsset)
AssetLinks.objects.filter(high=212)[0].low
When I do the filter above, how can I know which instance the objects is (website or service)? 当我执行上面的过滤器时,如何知道对象是哪个实例(网站或服务)? Also, is there a way to avoid an N+1 query using
prefetch_related
in a way that it gets all the child information as well? 另外,有没有办法避免以
prefetch_related
的方式获取所有子信息的N + 1查询?
You can even use select_related
instead of prefetch_related
. 您甚至可以使用
select_related
而不是prefetch_related
。 Something like this should do the trick: 这样的事情应该可以解决问题:
asset = AssetLinks.objects.filter(high=212).select_related(
'high__service', 'high__website',
'low__service', 'low__website',
)[0]
#check for service/website
service = getattr(asset.high, 'service', None)
website = getattr(asset.high, 'website', None)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.