0

I would like to replace null value in my django objects with the default value :

Example :

class Buy(models.Model):
    created = models.DateTimeField(null=True, blank=True, editable=False,default=timezone.now)
    modified = models.DateTimeField(null=True, blank=True,default=timezone.now)
    name = models.CharField(null=True,blank=True,  max_length=200,default='')

Here is my script :

for buy in Buy.objects.all():
    for f in Buy._meta.get_fields():
        field = eval("buy." + f.name+" is None")
        if field:
            field = Buy._meta.get_field(f.name).get_default()
        buy.save()

but when i make a json export with dumpdata i still have

"name" : null,

in my json for a lot of objects instead of

"name": ""

.

I don't understand my script for migrating the null value of my object to "" seems to be correct.

Regards

5
  • if field only runs if the field is not null, did you mean if not field? Commented Sep 16, 2020 at 12:33
  • @mousetail i've made a doncidtion before : field = eval("buy." + f.name+" is None") Commented Sep 16, 2020 at 12:35
  • 1
    Oh I see. But that won't work. field is a local variable. Changing it will have no effect. Why not use getattr and setattr rather than eval? Commented Sep 16, 2020 at 12:37
  • @mousetail i will dig your suggestion Commented Sep 16, 2020 at 12:39
  • @mousetail i think you're right i'am testing it right now if you want make an answer with your comment and i will validate it thanks :) Commented Sep 16, 2020 at 12:44

1 Answer 1

1

First of, don't use eval, since it is unsafe. 99% of the time there is a better way.

Secondly, changing a local variable will have no effect. The replaced value will be destroyed when the function returns and the stack frame is popped.

So, I suggest using getattr() and setattr() to perform your query:

setattr(buy, f.name, getattr(buy, f.name) or Buy._meta.get_field(f.name).get_default())
buy.save()

This oneliner will replace any falsy values with the default value, through the magic of or. Then we can use setattr to assign the correct value to the correct attribute. No eval needed.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.