skip to Main Content

If i have two models:

Model_1.objects.all()

Model_2.objects.all()

Model_1 contains all the elements, Model_2 contains a part of these elements.

How can i find the elements contained in Model_1 but not in Model_2?

I tried:

Model_1.objects.exclude(pk=Model_2.objects.order_by('pk'))

It doesn’t work.

2

Answers


  1. You can use in[Django doc.] like:

    Model_1.objects.exclude(pk__in=[obj.pk for obj in Model_2.objects.all()])
    
    Login or Signup to reply.
  2. Generally, 2 models represent two different entities. But if you want to filter the Model_1 based on some property of Model_2
    Use exclude and filter as per your requirement.

    Model_1.objects.exclude(id__in=Model_2.objects.all())
    Model_1.objects.filter(id__in=Model_2.objects.all())

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search