Real Quick
Real Quick

Reputation: 2800

Filter Django model with json values

I have this function:

# create a function to upload an object one to one given a json
def upload_object_values(model, json_values, update_if_exists=True):
    if json_values:
        # the json values contain key value that match to the model
        # use a copy to avoid runtime error dictionary changing size
        for json_value in json_values.copy():
            # remove all ids in model copy
            if json_value[-3:] == '_id' or json_value == 'id':
                json_values.pop(json_value)

        # 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 is get or create, or an update if exists
        if update_if_exists:
            # if it exists
            if model.__class__.objects.seal().exists():
                # retrieve the existing object
                retrieved_object = model.__class__.objects.seal().filter(json_values).first() #TODO: filter the model with the json_values
                # assign values into it
                retrieved_object = model
                # save
                retrieved_object.save()
                print(retrieved_object)
                print('existing, saved successfully')
            # if it does not exist
            else:
                # save
                model.save()
                print('does not exist, saved successfully')
        # else just save
        else:
            model.save()
            print('created successfully')

with sample json_values like:

{'notes': '', 'name': 'test issuer', 'phone': None}

I need to be able to filter using the json_values that I have, as shown in the line:

retrieved_object = model.__class__.objects.seal().filter(json_values).first() #TODO: filter the model with the json_values

How may I able to assign these values inside the filter() in django?

Upvotes: 0

Views: 85

Answers (2)

Nicolas Perez
Nicolas Perez

Reputation: 354

I think I understand what you are trying to achieve. Try this:

retrieved_object = model.__class__.objects.seal().filter(**json_values).first()

if json_values = {'notes': '', 'name': 'test issuer', 'phone': None}, the above line is equivalent to:

retrieved_object = model.__class__.objects.seal().filter(notes='', name='test issuer', phone=None).first()

Upvotes: 1

NixonSparrow
NixonSparrow

Reputation: 6378

To filter by JSONField in Django you should use __ (double).

YourObject.objects.filter(json_values__notes='')

YourObject.objects.filter(json_values__name='test issuer')

If you want to have deeper dict levels, the rule stays the same:

{'notes': {'casual': 'nice', 'pro': 'elegant'}, 'name': 'test issuer', 'phone': None}

YourObject.objects.filter(json_values__notes__pro='elegant')

Upvotes: 1

Related Questions