Home > OS >  Iterate through fields using array Django
Iterate through fields using array Django

Time:06-21

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

CodePudding user response:

You likely want to mimic .update_or_create(…) [Django-doc]. You can do this with:

def upload_object_values(model, json_values, keys=None):
    model._base_manager.update_or_create(
        **{key: json_values[key] for key in keys},
        defaults={key: value for key, value in json_values.items() if key not in keys}
    )

You should here work with a reference to the model class, so not a model object:

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

Note: Models in Django are written in PascalCase, not snake_case, so you might want to rename the model from Some_model to SomeModel.

  • Related