Filtering objects and and their instances using filter and exclude

Viewed 35

I am trying to filter like this:

#models.py
class A(models:Model):
    all_letters = models.ManyToManyField(Letters, related_name="all_letters")
    selected_letters = models.ManyToManyField(Letters, related_name="selected_letters")
#views.py
a = A.objects.get(pk=pk)
array_one = a.all_letters.all().exclude(a.selected_letters.all())

I know you can't filter based on instances but is the only equivalent way of doing this using some sort of manual python searching?

1 Answers

You can filter out the items where the relation in reverse (which you also named selected_letters) do not point to a, so:

array_one = a.all_letters.exclude(selected_letters=a)
Related