Yuri Heupa
Yuri Heupa

Reputation: 1248

Django - Query models where id equals attribute on python list

I need to query all models where the ID matches the 'id' attribute of JSON array, something like that:

I have 3 saved model objects with respective ID's:

ID 1
ID 3
ID 4

I have a JSON array like that:

[{'id' : 1}, {'id' : 2}, {'id' : 5}]

I want to filter in that way:

model.objects.filter('Objects by ID that is not listed in the JSON array')

The result of the filter should be a list with models objects that the ID is not in the JSON:

result = [model_pk=3, model_pk=4]

Any ideas?

Upvotes: 0

Views: 328

Answers (1)

Aamir Rind
Aamir Rind

Reputation: 39659

You can use exclude method to achieve that:

ids = [i['id'] for i in json_array]
qs = model.objects.exclude(id__in=ids)

Upvotes: 3

Related Questions