Created
May 19, 2012 14:37
-
-
Save zelid/2731053 to your computer and use it in GitHub Desktop.
Allow to create new model with related models in Flask-Peewee API call
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def get_models_from_dictionary(model, field_dict): | |
| if isinstance(model, Model): | |
| model_instance = model | |
| check_fks = True | |
| else: | |
| model_instance = model() | |
| check_fks = False | |
| models = [model_instance] | |
| for field_name, value in field_dict.items(): | |
| field_obj = model._meta.fields[field_name] | |
| if isinstance(value, dict): | |
| rel_obj = field_obj.to # here we can get related object type, to not be None | |
| if check_fks: | |
| try: | |
| rel_obj = getattr(model, field_name) # when create rel object - it will be None | |
| except field_obj.to.DoesNotExist: | |
| pass | |
| ### my add | |
| if rel_obj is None: | |
| rel_obj = field_obj.to # RelatedOneToOneModel if new model passed as Json and not FK int Id | |
| ### end my add | |
| rel_inst, rel_models = get_models_from_dictionary(rel_obj, value) | |
| models.extend(rel_models) | |
| setattr(model_instance, field_name, rel_inst) | |
| else: | |
| setattr(model_instance, field_name, field_obj.python_value(value)) | |
| return model_instance, models |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment