[Answered ]-Create model instance from dict containing different keys compared to model attributes in Django

1👍

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)

Leave a comment