在列表理解中绕过 NoneType

Bypassing NoneType in a list comprehension

为了解决没有值 x.competition.name 时的问题,我尝试使用 is not None:

'competition': [x.competition.name if x.competition.name is not None else '-' for x in a]

但错误仍然不断出现:

AttributeError: 'NoneType' object has no attribute 'name'

我该如何解决这个问题?

听起来你需要测试 x.competition:

'competition': [x.competition.name if x.competition is not None else '-' for x in a]

显然竞争是None,所以请替换

[x.competition.name if x.competition.name is not None else '-' for x in a]

使用

[x.competition.name if x.competition is not None else '-' for x in a]

错误消息说您试图获取 None.name。这意味着 x.competition 必须是 None,这就是为什么您无法从中获取 name 属性的原因。相反,请尝试使您的条件 x.competition is not None.