I am trying to upload data in the django ORM by a script for which I have written this
for index, row in df.iterrows():
allocated = row['is_allocated']
delivery_required_on = row['delivery_required_on']
linked = row['linked']
raised_by = row['raised_by']
raised_for = Company.objects.get(pk=row['raised_for']) ### double check
rejected = row['is_rejected']
reason = row['reason']
remarks = row['remarks']
created = row['created_at']
owner = User.objects.get(pk=row['New owner'])
j = literal_eval(row['flows'])
flows = []
mobj = MaterialRequest.objects.create(owner=owner, is_allocated=allocated,
delivery_required_on=delivery_required_on, linked=linked,
raised_by=raised_by, raised_for=raised_for, is_rejected=rejected,
reason=reason, remarks=remarks, created=created)
It is running fine when the data is something like the following:
But as soon as is_allocated
reaches False
it shows the following error:
django.core.exceptions.ValidationError: ['“TRUE” value must be either True or False.']
I am unable to find something related to this
CodePudding user response:
it seems like the is_allocated
property of your model is a boolean. So you should assign a boolean value to it. But your column values in the data frame are strings TRUE
and FALSE
.
replacing this line
allocated = row['is_allocated']
with
allocated = (row['is_allocated'] == 'TRUE')
might help.
if you have None
other than True
and False
values, consider that too.
CodePudding user response:
It is because you are trying to store a string in a boolean field. One solution is to change your string type to boolean. Maybe having a function like following in your code solves your problem:
def to_boolean(raw_value: str) -> bool:
if not isinstance(raw_value, str):
raw_value = str(raw_value)
raw_value = raw_value.strip()
return {'true': True, 'false': False}.get(raw_value.lower(), False)
and then use it in your loop like (where ever you think your field type is boolean):
for index, row in df.iterrows():
allocated = to_boolean(row['is_allocated'])
delivery_required_on = row['delivery_required_on']
linked = row['linked']
raised_by = row['raised_by']
raised_for = Company.objects.get(pk=row['raised_for']) ### double check
rejected = to_boolean(row['is_rejected'])
reason = row['reason']
remarks = row['remarks']
created = row['created_at']
owner = User.objects.get(pk=row['New owner'])
j = literal_eval(row['flows'])
flows = []
mobj = MaterialRequest.objects.create(owner=owner, is_allocated=allocated,
delivery_required_on=delivery_required_on, linked=linked,
raised_by=raised_by, raised_for=raised_for, is_rejected=rejected,
reason=reason, remarks=remarks, created=created)