appengine: ReferencePropertyResolveError: ReferenceProperty failed to be resolved: [u'User', xxxxxxxxxxxxx]

appengine: ReferencePropertyResolveError: ReferenceProperty failed to be resolved: [u'User', xxxxxxxxxxxxx]

我有获取参与者并显示他们的代码。控制视图的逻辑如下:

    def fetch_participants(self, count=12):
        memcache_key = 'mission_participants:%d:%d' % (self.key().id(), count)
        participants = utils.deserialize_entities(memcache.get(memcache_key))
        if participants is None:
            participants = self.fetch_participants_datastore(count)
            memcache.set(memcache_key, utils.serialize_entities(participants), 3600)
        return participants

问题是 appengine 抛出以下错误:

  File "site/templates/participant_base.html", line 209, in block "content"
    {% set participants = mission.fetch_participants(40) %}
  File "/base/data/home/apps/proj/32.424491487021355902/models/mission.py", line 311, in fetch_participants
    participants = self.fetch_participants_datastore(count)
  File "/base/data/home/apps/proj/32.424491487021355902/models/mission.py", line 301, in fetch_participants_datastore
    users = [join.user for join in joins]
  File "/base/alloc/tmpfs/dynamic_runtimes/python27g/9fae800fb98bd45d/python27/python27_lib/versions/1/google/appengine/ext/db/__init__.py", line 3734, in __get__
    reference_id.to_path())
ReferencePropertyResolveError: ReferenceProperty failed to be resolved: [u'User', xxxxxxxxxxx]

错误似乎是这一行:

participants = self.fetch_participants_datastore(count)

Whosebug 上的一位用户提出了类似的问题:

This happens when you attempt to resolve a reference property (by dereferencing it - for instance, (MyModel.MyReferenceProp.foo), and the property being referenced no longer exists - because it has been deleted.

You need to modify your code to catch this exception when you dereference an entity that may have been deleted, and handle it appropriately.

我想我必须做类似的事情,问题是我不知道如何修改代码来捕获异常。您是否可以过滤参与者以不包括引用的参与者?有更好的选择吗?

def fetch_participants_datastore(self, count=12):
    joins = self.mission_joins.order('-created').fetch(count * 2)
    utils.prefetch_refprops(joins, MissionJoin.user)
    users = [join.user for join in joins]
    with_avatars = [user for user in users if user.has_avatar()]
    without_avatars = [user for user in users if not user.has_avatar()]
    users = with_avatars + without_avatars
    return users[:count]

编辑:

for join in joins:
     try:
          users = join.user
     except:
          pass

将代码的第 301 行打断为一个 for 循环,并在包含 join.user

的行周围添加一个 try/except 块