Filtering objects and and their instances using filter and exclude

I am trying to filter like this:
class A(models:Model):
    all_letters = models.ManyToManyField(Letters, related_name="all_letters")
    selected_letters = models.ManyToManyField(Letters, related_name="selected_letters")
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?


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)

Leave a Reply

Your email address will not be published. Required fields are marked *