gpt4 book ai didi

python - 属性错误 : object has no attribute 'pk'

转载 作者:行者123 更新时间:2023-12-05 04:26:02 25 4
gpt4 key购买 nike

我正在尝试通过 Django 和 Django Rest Framework 将一些数据插入 MySQL 数据库(模型 LogsSeparate),但我一直收到一个错误,我打赌这个错误很容易解决,但我自己无法弄清楚:

错误:

if obj.pk is None:

AttributeError: 'LogObjTest' object has no attribute 'pk'

代码:

class LogObjTest():          
def __init__(self):
self._id = None
self.bits = None
class getLogs(viewsets.ModelViewSet):
arrayTest=[]
for x in Logs.objects.all():
serializer_class = LogsSeparateSerializer
test = Fields.objects.filter(pac_id=x.message_id_decimal)
binaryTest=x.data_binary

for i in test:
obj=LogObjTest()
obj._id=x.message_id_decimal
obj.bits=binaryTest[i.fld_offset:i.fld_offset+i.fld_len]
arrayTest.append(obj)


queryset = arrayTest
LogsSeparate.objects.bulk_create(arrayTest)

print("arrayTest",arrayTest)

模型.py

class LogsSeparate(models.Model):
_id = models.CharField(max_length=255, primary_key=True, null=False, db_column='_id')
bits = models.CharField(max_length=500, db_column='bits')

def __str__(self):
return self.bits```

最佳答案

不要使用 LogObjTest。导入您在 model.py 文件中创建的 LogsSeparate,然后使用它创建一个新对象。

class getLogs(viewsets.ModelViewSet):
arrayTest=[]
for x in Logs.objects.all():
serializer_class = LogsSeparateSerializer
test = Fields.objects.filter(pac_id=x.message_id_decimal)
binaryTest=x.data_binary

for i in test:
obj=LogsSeparate(_id=x.message_id_decimal, bits=binaryTest[i.fld_offset:i.fld_offset+i.fld_len])
arrayTest.append(obj)


queryset = arrayTest
LogsSeparate.objects.bulk_create(arrayTest)

print("arrayTest",arrayTest)

关于python - 属性错误 : object has no attribute 'pk' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73116131/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com