我有以下定义的模型:
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
当我执行上面的过滤器时,如何知道对象是哪个实例(网站或服务)?另外,有没有办法避免使用prefetch_related
进行N + 1查询,以便获取所有子信息?
答案 0 :(得分:0)
您甚至可以使用select_related
代替prefetch_related
。这样的事情可以解决问题:
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)