116 | def dict_to_filter_params(d, prefix=''): |
117 | """ |
118 | Translate a dictionary of attributes to a nested set of parameters suitable for QuerySet filtering. For example: |
119 | |
120 | { |
121 | "name": "Foo", |
122 | "rack": { |
123 | "facility_id": "R101" |
124 | } |
125 | } |
126 | |
127 | Becomes: |
128 | |
129 | { |
130 | "name": "Foo", |
131 | "rack__facility_id": "R101" |
132 | } |
133 | |
134 | And can be employed as filter parameters: |
135 | |
136 | Device.objects.filter(**dict_to_filter(attrs_dict)) |
137 | """ |
138 | params = {} |
139 | for key, val in d.items(): |
140 | k = prefix + key |
141 | if isinstance(val, dict): |
142 | params.update(dict_to_filter_params(val, k + '__')) |
143 | else: |
144 | params[k] = val |
145 | return params |