Skip to main content
 首页 » 编程设计

python 细节 : Array value must start with "{" or dimension information

2024年11月24日8xing901022

我试图将一个字符串添加到 ArrayField 中,但我得到了 DETAIL: Array value must start with "{"or dimension information. 错误。

这就是模型看起来像方法 update_credential 是我尝试将 merchant_id 添加到商家 ArrayField 的地方。

class CloverCredential(models.Model): 
    tenant = models.OneToOneField('tenant.Tenant', unique=True, on_delete=models.CASCADE) 
    token = EncryptedCharField(max_length=255, null=True) 
    spreedly_receiver_token = EncryptedCharField(max_length=255, null=True) 
    merchants = ArrayField(models.CharField(max_length=200, blank=True), null=True) 
 
    def update_credential(self, new_token, merchant_id): 
        self.token = new_token 
        self.merchants = merchant_id 
        self.save() 

这是我调用 update_credential 并传递 token 和 merchant_id

的 View
class OAuthCallback(APIView): 
    def api_request(self, path): 
        return requests.get(path).json() 
 
    def get(self, request, *args, **kwargs): 
        code = request.GET.get('code', '') 
        state = unsign_state(request.GET.get('state', '')) 
        merchant_id = request.GET.get('merchant_id', '') 
        tenant = get_object_or_404(Tenant, pk=state['tenant_id']) 
        clover_credential, created = CloverCredential.objects.get_or_create(tenant=tenant) 
 
        url = f'{settings.CLOVER_URL_US}/oauth/token?client_id={settings.CLOVER_APP_ID}&client_secret={settings.CLOVER_APP_SECRET}&code={code}' 
        oauth_response = self.api_request(url) 
        clover_credential.update_credential(oauth_response['access_token'], merchant_id) 
        return redirect(state['redirect']) 

我还尝试将 merchant_id 附加到商家 self.merchants.append(merchant_id) 并得到这个错误 AttributeError: 'NoneType' 对象没有属性 'append'

请您参考如下方法:

问题
merchants 字段是一个列表,但默认情况下它是空的。

解决方案
所以最好的办法是设置一个 default=list。

错误解释

Array value must start with "{" or dimension information.

发生这种情况是因为您将一个变量放入列表中,而不是这样做 self.merchants = [merchant_id, ]

'NoneType' object has no attribute 'append'

发生这种情况是因为您有一个 None,而不是一个列表。将空列表设为默认值或通过代码设置:self.merchants = list()