【问题标题】:django prefetch_related not workingdjango prefetch_related 不工作
【发布时间】:2013-07-29 07:53:07
【问题描述】:

我正在尝试使用 prefetch_related 导出我的所有数据库,但我只从主模型中获取数据。 我的模型:

class GvtCompoModel(models.Model):
    gvtCompo= models.CharField(max_length=1000, blank=False, null=False)
    ...

class ActsIdsModel(models.Model):
    year = models.IntegerField(max_length=4, blank=False, null=False)
    ...

class RespProposModel(models.Model):
    respPropos=models.CharField(max_length=50, unique=True)
    nationResp = models.ForeignKey('NationRespModel', blank=True, null=True, default=None)
    nationalPartyResp = models.ForeignKey('NationalPartyRespModel', blank=True, null=True, default=None)
    euGroupResp = models.ForeignKey('EUGroupRespModel', blank=True, null=True, default=None)

class ActsInfoModel(models.Model):
    #id of the  act
    actId = models.OneToOneField(ActsIdsModel, primary_key=True)
    respProposId1=models.ForeignKey('RespProposModel', related_name='respProposId1', blank=True, null=True, default=None)
    respProposId2=models.ForeignKey('RespProposModel', related_name='respProposId2', blank=True, null=True, default=None)
    respProposId3=models.ForeignKey('RespProposModel', related_name='respProposId3', blank=True, null=True, default=None)
    gvtCompo= models.ManyToManyField(GvtCompoModel)

我的看法:

dumpDB=ActsInfoModel.objects.all().prefetch_related("actId", "respProposId1", "respProposId2", "respProposId3", "gvtCompo")
for act in dumpDB.values():
    for field in act:
        print "dumpDB field", field

当我显示“字段”时,我只看到来自 ActsInfoModel 的字段,即起始模型。正常吗?

【问题讨论】:

    标签: django one-to-many one-to-one manytomanyfield prefetch


    【解决方案1】:

    您还没有理解 prefetch_related 的参数。它不是字段列表,而是模型列表。

    (请注意,您的字段命名约定也非常具有误导性 - respProposId1 和 actId 不是 ID,而是模型的实际实例。Django 通过附加 _id 在每种情况下创建了一个基础字段,因此 db 列是 respProposId1_id 和 actId_id . 你应该只调用字段 resp_propos1 和 resp_propos2 - 另请注意,正常样式是 lower_case_with_underscore,而不是 capWords。)

    【讨论】:

    • 感谢您的建议。
    【解决方案2】:

    您只能看到来自ActsInfoModel 的字段,这很正常。您可以通过点符号访问相关模型,例如:

    acts = ActsInfoModel.objects.all().prefetch_related("actId", "respProposId1", "respProposId2", "respProposId3", "gvtCompo")
    for act in acts:
        print act.respProposId1.respPropos
    

    相关模型已经预取,因此不会产生任何额外的查询。仅供参考,引用自docs

    返回一个将自动检索的 QuerySet,在单个 每个指定查找的批处理相关对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-07
      • 2020-06-06
      • 2013-09-26
      • 1970-01-01
      • 2016-11-28
      • 2018-05-19
      • 2014-09-01
      • 2019-08-07
      相关资源
      最近更新 更多