Home > Back-end >  How to djanog orm filter reverse foreign key
How to djanog orm filter reverse foreign key

Time:11-12

When I use django, I created two models.

class GroupModel(models.Model):
    group_name = models.CharField(max_length=2, null=False, default="A")


class MemberModel(models.Model):
    name = models.CharField(max_length=8, null=False, default="")
    group = models.ForeignKey(
        to=GroupModel,
        on_delete=models.CASCADE,
        related_name="members",
        db_column="member",
    )
    isActive = models.BooleanField(null=False, default=False)

The contents lisk:

[{'group_name': 'GROUP_A',
  'id': 1,
  'members': [{'isActive': False, 'name': 'j'},
              {'isActive': True, 'name': 'b'},
              {'isActive': True, 'name': 'y'}]},
 {'group_name': 'GROUP_B',
  'id': 2,
  'members': [{'isActive': True, 'name': 'f'},
              {'isActive': True, 'name': 'i'},
              {'isActive': True, 'name': 'y'}]}]

Now, I want to get the queryset wiht isActive=False

queryset = GroupModel.objects.filter(members__isActive=False).distinct()

but the resutl is

[{'group_name': 'GROUP_A',
  'id': 1,
  'members': [{'isActive': False, 'name': 'j'},
              {'isActive': True, 'name': 'b'},
              {'isActive': True, 'name': 'y'}]}]

How I can get the expected result list

[{'group_name': 'GROUP_A',
  'id': 1,
  'members': [{'isActive': False, 'name': 'j'}]}]

CodePudding user response:

I think you should use MemberModel instead on GroupModel class in your queryset

queryset = MemberModel.objects.filter(isActive=False).distinct()
for objects in queryset:
    print(objects.name)

Thank you

CodePudding user response:

You can filter the relation as well with a Prefetch object [Django-doc]:

from django.db.models import Prefetch

queryset = GroupModel.objects.filter(
    members__isActive=False
).prefetch_related(
    Prefetch('members', MemberModel.objects.filter(isActive=False))
).distinct()
  • Related