Reputation: 515
I am trying to create model/s from an api response. The response received has different keys as compared to the model attributes in our system. I would like to know the best way to create a model from that response.
class MyModel(BaseModel):
external_id = models.IntegerField(blank=True, null=True)
start_date = models.DateField(blank=True, null=True)
end_date = models.DateField(blank=True, null=True)
def save_to_db_from_external_data(response_data):
map_dict = {
'externalId': 'external_id',
'startDate': 'start_date',
'endDate': 'end_date'
}
if type(response_data) == 'dict':
new_model_data_dict = {}
for key in map_dict:
if key in response_data:
new_model_data_dict[map_dict[key]] = response_data[key]
MyModel.objects.create(**new_model_data_dict)
elif type(response_data) == 'list':
new_model_data_list = []
for data_dict in response_data:
new_data_dict = {}
for key in map_dict:
if key in data_dict:
new_data_dict[map_dict[key]] = data_dict[key]
new_model_data_list.append(new_data_dict)
MyModel.objects.create(**(model_data_dict) for model_data_dict in new_model_data_list)
The above is the code that I have written. Is this the correct way to do the required task? Or is there any better way in django to achieve the same?
Upvotes: 1
Views: 58
Reputation: 711
Your solution looks fine.
Tip: avoid to copy and paste code pieces. Try to use functions and classes wherever you can.
class MyModel(BaseModel):
external_id = models.IntegerField(blank=True, null=True)
start_date = models.DateField(blank=True, null=True)
end_date = models.DateField(blank=True, null=True)
def create_object_from_external_data(response_data):
MyModel.objects.create(
external_id=response_data.get('externalId'),
start_date=response_data.get('startDate'),
end_date=response_data.get('endDate')
)
def save_to_db_from_external_data(response_data):
if type(response_data) == 'dict':
self.create_object_from_external_data(response_data)
elif type(response_data) == 'list':
for data_dict in response_data:
self.create_object_from_external_data(data_dict)
Upvotes: 1