#36291 closed Bug (worksforme)
ManyToManyField empty when setting related_name and related_query_name to "+"
Description ¶
I’ve encountered an issue in my Django project where using the following configuration in a ManyToManyField causes the field to return an empty queryset—even though the underlying join table contains records. Notably, this bug appears to be intermittent; sometimes the field behaves as expected, while other times it consistently returns an empty queryset.
move_lines = models.ManyToManyField( "accounting.AccountMoveLine", verbose_name="Move Lines", related_name="+", related_query_name="+", blank=True, )
Steps to Reproduce:
Define a model with a ManyToManyField that includes related_name="+" and related_query_name="+" (to disable reverse relations).
Create and save related records so that there are entries in the join table.
Query the field using instance.move_lines.all().
Observe that the queryset is empty despite the related records existing. Note that the bug does not occur consistently—there are occasions where the field returns the expected records.
Expected Behavior:
The field should return all associated records when queried, regardless of the reverse relation being disabled.
Actual Behavior:
When related_name and related_query_name are set to "+", instance.move_lines.all() sometimes returns an empty queryset even though related records exist. Removing these attributes (thus allowing Django to generate default reverse names) consistently resolves the issue.
Additional Context:
This appears to be an issue where disabling the reverse relationship by setting the related names to "+" intermittently interferes with the ORM’s ability to construct the proper join, resulting in an empty result set on the forward lookup. Has anyone else experienced this behavior, or is there a known workaround or fix for this issue?
Thanks in advance for any help or insights!
I cannot replicate, can you try to write a regression test?
This was what I have tested:
TabularUnified tests/m2m_regress/models.py
TabularUnified tests/m2m_regress/tests.py