【问题标题】:Accessing child from parent从父母访问孩子
【发布时间】:2017-05-08 18:37:26
【问题描述】:

我有以下定义的模型:

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 查询,同时获取所有子信息?

【问题讨论】:

    标签: python django django-models django-orm


    【解决方案1】:

    您甚至可以使用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)
    

    【讨论】:

    • Service and Website extend from PrimaryAsset and AssetLinks has FKs to PrimaryAsset
    猜你喜欢
    • 2014-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多