I am trying to insert some data into MySQL database (model LogsSeparate) through Django and Django Rest Framework but I keep getting an error which I bet is very easy to solve yet I couldn't figure it out myself:
Error:
if obj.pk is None:
AttributeError: 'LogObjTest' object has no attribute 'pk'
Code:
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)
models.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```
CodePudding user response:
Don't use LogObjTest
. Import LogsSeparate
that you created in the model.py file then use it to create a new object.
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)