[Answered ]-Using setattr() to set None or blank value

1👍

To set a value to the ForeignKey you need an object.

ValueError: Cannot assign "”": "MyModel.attr_name" must be a
"MyAttrModel" instance.

You can use instead an attribute with _id at the end.

none_attributes = ['attr_name_id', 'attr2_name_id', 'attr3_name_id']

for attr in none_attributes:
    setattr(instance, attr, "")

Behind the scenes, Django appends "_id" to the field name to create its database column name, see Django ForeignKey

Also as @Willem pointed out, you should to check that none_attributes are iterable.

TypeError: ‘NoneType’ object is not iterable

from collections.abc import Iterable

if isinstance(none_attributes, Iterable):
    for attr in none_attributes:
        setattr(instance, attr, None)
👤NKSM

Leave a comment