Фильтр модели Django с помощью json-значений

У меня есть такая функция:

# 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')

с примерами json_values, такими как:

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

Мне нужно иметь возможность фильтровать, используя json_values, которые у меня есть, как показано в строке:

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

Как я могу присвоить эти значения внутри filter() в django?

Для фильтрации по JSONField в Django следует использовать __ (double).

YourObject.objects.filter(json_values__notes='')

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

Если вы хотите иметь более глубокие уровни диктовки, правило остается прежним:

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

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

Мне кажется, я понимаю, чего вы пытаетесь достичь. Попробуйте следующее:

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

if json_values = {'notes': '', 'name': 'test issuer', 'phone': None}, приведенная выше строка эквивалентна:

retrieved_object = model.__class__.objects.seal().filter(notes='', name='test issuer', phone=None).first()
Вернуться на верх