Created
May 17, 2020 08:23
-
-
Save dorosch/3a1220c0b9c52eb5fa288b571d63cca0 to your computer and use it in GitHub Desktop.
Provide mapping model to json and back with custom fields
This file contains 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
import abc | |
from django.forms.models import model_to_dict | |
class Mapping(abc.ABC): | |
model = None | |
fields = {} | |
@classmethod | |
def json_to_model(cls, json): | |
return cls.model( | |
**{ | |
field: json.get(mapped) | |
for field, mapped in cls.fields.items() | |
if json.get(mapped) | |
} | |
) | |
@classmethod | |
def model_to_json(cls, instance): | |
return { | |
cls.fields[field]: value | |
for field, value in model_to_dict( | |
instance, fields=list(cls.fields) | |
).items() | |
} | |
@classmethod | |
def update_model(cls, instance, json): | |
for field, mapped in cls.fields.items(): | |
value = json.get(mapped) | |
if value: | |
setattr(instance, field, value) | |
instance.save() | |
class PositionMapping(Mapping): | |
model = Position | |
fields = { | |
'ext_position_id': 'ext_position_id', | |
'delivery_order': 'delivery_order_id', | |
'consignment': 'consignment_id' | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment