marshmallow-sqlalchemy icon indicating copy to clipboard operation
marshmallow-sqlalchemy copied to clipboard

Setting instance attribute with function during deserialization?

Open YKdvd opened this issue 9 years ago • 6 comments

I have a Parent class, with a Child class as a standard one-many relationship ("Parent.children"). The Child class has a field call "specialVal", which needs some extra logic when it is changed. I have a "setSpecialVar()" method that does this internally. But when doing deserialization, the value of "specialVar" is just simply set by the deserializer, and my method obviously isn't called.

By the time "load()" comes back with the Parent instance, SQLAlchemy's flush has been called, probably for each child, which wipes out the change history and there seems to be no way to get the "old" value of "specialVal", so I can't even change it back and call "setSpecialVar()" to do the "right" thing (the logic depends on the current and new value of the variable).

There doesn't seem to be any sort of hook to define a "setter" for a specific field as an instance is being made? It looks like "make_instance()" is a Marshmallow post_load method, and is just doing a plain "setattr()" in a loop with the data passed to it. Would my best bet be to define a custom "make_instance" for Child, copying most of the code but calling my setSpecialVar() method instead of "setattr" when the key is "specialVar"?

YKdvd avatar Jul 10 '17 15:07 YKdvd

Actually, when adding my own "post_load"-decorated method on Parent or Child, it receives the data parameter as an instance - mmsqla's make_instance() has already created it. But things have already been flushed as the children were deserialized, and by the time my own method gets called, sqlalchemy.orm.attributes.get_history() shows the new value, as "unchanged", and the old value is unavailable.

It looks like I'd have to override make_instance() (perhaps in a custom descendant of ModelSchema), and somehow have registered some indication of what it should do for special fields (put name of a method to call in the field's "metadata", perhaps). I'm not missing some obvious way to do this sort of custom "setter" routine?

YKdvd avatar Jul 10 '17 17:07 YKdvd

@YKdvd I've just encountered the same problem. Did you come up with a solution?

bac avatar Sep 22 '17 11:09 bac

I created a subclass of ModelSchema, and did something like this in the constructor:

		self.complexSetterFields = {}	# a dict of any fields that need to be set with a function
		for key,field in self.fields.items():
			metadata = getattr(field, "metadata", None)
			if metadata and 'complexSetter' in field.metadata:
				self.complexSetterFields[key] = field.metadata['complexSetter']

Then I did my own make_instance():

	@ma.post_load
	def make_instance(self, data):
		instance = self.instance or self.get_instance(data)
		if instance is not None:
			if self.complexSetterFields:
				for key, value in iteritems(data):
					if key in self.complexSetterFields:
						curr = getattr(instance, key)
						if curr == value:
							pass   # skip setting to existing value
						else:
							ourMethod = self.complexSetterFields[key]
							ourMethod(data, instance, key, value)
							db.session.flush()
					else:   # simply set, like original mm code
						setattr(instance, key, value)
			else:    # normal mm code
				for key, value in iteritems(data):
					try:
						setattr(instance, key, value)
					except:
						print "Error setting [%s] attribute '%s'"%(type(instance), key)
						raise
					#sqlalchemy.orm.attributes.set_attribute(instance, key, value)
			return instance
		
		instance = self.opts.model(**data)
		return instance

Now I can do something like this when defining a schema:

	myComplexField = ma.fields.Number(complexSetter=lambda data,instance,key,val: setattr(instance, key, val*2 if instance.shouldWeDouble else val) )

So I'm passing a function (a lambda in this case) as "complexSetter=" that takes those 4 parameters, and it will get called by my customized make_instance(). In this demo it is a simple check of an attribute on the instance and doubles the value if it is True, but it could do whatever is needed with the original value. This is a bit of a hack, and I didn't dig into the MM internals enough to know if it might fail outside of my simple needs.

YKdvd avatar Sep 26 '17 14:09 YKdvd

Don't you just need to follow this example and make the field in your schema a method or function? http://marshmallow.readthedocs.io/en/latest/custom_fields.html

zerox1212 avatar Nov 03 '17 19:11 zerox1212

You have probably solved this issue already anyways, but you might also want to look into SQLAlchemy's hybrid attributes.

joelhed avatar Aug 08 '18 10:08 joelhed

Closing, as this issue has gone stale. Feel free to comment if further discussion is needed.

sloria avatar Sep 06 '19 01:09 sloria