Home > Software design >  How to filter reverse foreign key with more one conditions by prefetch_related in Django
How to filter reverse foreign key with more one conditions by prefetch_related in Django

Time:11-18

I created tow 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)
    country = models.CharField(max_length=8, null=False, default="CN")

I run

queryset = GroupModel.objects.prefetch_related(
    Prefetch("members", MemberModel.objects.filter(isActive=False))
).distinct()

I got the all groups with the field isAcitve is Flase in MemberModel.

Now, I want to get all groups with the field isActive is False and country is CN in MemberModel.

I run

queryset = GroupModel.objects.prefetch_related(
    Prefetch("members", MemberModel.objects.filter(isActive=False, country="CN"))
).distinct()

But I get the result is

[{'group_name': 'GROUP_A', 'id': 1, 'members': []},
 {'group_name': 'GROUP_B', 'id': 2, 'members': []},
 {'group_name': 'GROUP_C',
  'id': 3,
  'members': [{'country': 'CN', 'isActive': False, 'name': 'ENWK'},
              {'country': 'CN', 'isActive': False, 'name': 'LKMP'}]}]

I want to get

[{'group_name': 'GROUP_C',
  'id': 3,
  'members': [{'country': 'CN', 'isActive': False, 'name': 'ENWK'},
              {'country': 'CN', 'isActive': False, 'name': 'LKMP'}]}]

What can I do?

CodePudding user response:

You should filter the GroupModel as well, so:

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