2022-06-27

Iterate through fields using array Django

I have this model:

class Some_model(models.Model):
    field_1 = models.CharField(max_length=200, blank=True, null=True)
    field_2 = models.CharField(max_length=200, blank=True, null=True)

and this function:

# create a function to upload a model object given a json object
def upload_object_values(model, json_values, keys=None):
    if json_values:

        # assign a value to each key which is a the field in the given model
        for key, value in json_values.items():
            setattr(model, key, value)
        
        # if the object has keys to check
        if keys:
            # check if exists using the keys

when called like this:

upload_object_values(Some_model(), {'field_1': 'val', 'field_2': 'val_2'}, ['field_2'])

It would do a get or create inside the upload_object_values function using the fields inside the keys parameter (e.g.: field_2 as the parameter).

Some_model.objects.get_or_create(field_2='val_2')

UPDATE: enter image description here



No comments:

Post a Comment