Unsaved model instances to related filters in tests for django 5.0

In Django 5 “passing unsaved model instances to related filters is no longer allowed” (Django 5.0 release notes | Django documentation | Django).

Basically before I had this method (only relevant code shown):

def make_payload(user, nonce, exclude_groups=None):
    exclude_groups = set(exclude_groups or [])
    relevant_groups = Group.objects.filter(internal_only=False).order_by("internal_name")
    filter_q = Q(user=user) & ~Q(pk__in=exclude_groups)
    add_groups = relevant_groups.filter(filter_q).values_list("internal_name", flat=True)
    ...

And tested it using this test method (only relevant code shown):

def test_builds_payload_not_activated(self):
    user = accounts.tests.factories.UserFactory.build(email_verified=False)

    payload = utils.make_payload(user, "nonce-nce")
    ...

Now obviously the instance as not been saved as it’s a unit and not an integration test. This leads to relevant_groups.filter(filter_q) failing with ValueError: Model instances passed to related filters must be saved. Basically I’ve no idea how to fix the test as the code is still working in a real environment. Ideas welcome.

<conjecture>
You may be able to get past this by directly altering the ModelState object in that user.

Assuming you’ve assigned a pk for that object, I would try setting user._state.adding=False and user._state.db='default'
</conjecture>