async def test_prefetch_m2m_to_attr(self): tournament = await Tournament.create(name="tournament") team = await Team.create(name="1") team_second = await Team.create(name="2") event = await Event.create(name="First", tournament=tournament) await event.participants.add(team, team_second) event = await Event.first().prefetch_related( Prefetch("participants", Team.filter(name="1"), to_attr="to_attr_participants_1"), Prefetch("participants", Team.filter(name="2"), to_attr="to_attr_participants_2"), ) self.assertEqual(list(event.to_attr_participants_1), [team]) self.assertEqual(list(event.to_attr_participants_2), [team_second])
async def test_prefetch_m2m(self): tournament = await Tournament.create(name="tournament") event = await Event.create(name="First", tournament=tournament) team = await Team.create(name="1") team_second = await Team.create(name="2") await event.participants.add(team, team_second) fetched_events = (await Event.all().prefetch_related( Prefetch("participants", queryset=Team.filter(name="1"))).first()) self.assertEqual(len(fetched_events.participants), 1)
async def test_prefetch_m2m_filter(self): tournament = await Tournament.create(name="tournament") team = await Team.create(name="1") team_second = await Team.create(name="2") event = await Event.create(name="First", tournament=tournament) await event.participants.add(team, team_second) event = await Event.all().prefetch_related( Prefetch("participants", Team.filter(name="2"))).first() self.assertEqual(len(event.participants), 1) self.assertEqual(list(event.participants), [team_second])