Search code examples
pythondjangodjango-rest-frameworkdjango-orm

How to remove from QuerySet by some condition


I have a queryset, and lets say its described like this (in JSON)

{
  [
    {
      "name": "Alex",
      "01_correct_answers": 1,
      "02_correct_answers": 3,
    }, 
    {
      "name": "John",
      "01_correct_answers": null,
      "02_correct_answers": null,
    },
    {
      "name": "James",
      "01_correct_answers": null,
      "02_correct_answers": 3,
    },
  ]
}

Here 01 and 02 are subject IDs. And I have a list of these IDs, now how can I loop through this list of IDs and check the queryset if the correct_answers of the student for these subjects are not null, if they are null (all subjects), just remove them from the queryset. And finally I would like to have a filtered queryset like below:

{
  [
    {
      "name": "Alex",
      "01_correct_answers": 1,
      "02_correct_answers": 3,
    }, 
    {
      "name": "James",
      "01_correct_answers": null,
      "02_correct_answers": 3,
    },
  ]
}

I would like to do something like this

subjects = ['01', '02']
new_queryset = q.exclude(
  # for subject in subjects: f"{subject}_correct_answers"=None
)

Solution

  • You can query with:

    subjects = ['01', '02']
    
    new_queryset = q.exclude(
        Q(*[(f'{sub}_correct_answers', None) for sub in subjects])
    )