I don’t know much about prefetch and I may have missed something.
I use multiple many-to-many fields and declare the related_name with “+” to avoid creating reverse relationships.
This is a setting that cannot be changed.
The problem arises when using querysets with prefetch_related or call manytomany objects.
When I call an object belonging to a many-to-many relationship, the following error occurs.
django.core.exceptions.FieldError: Cannot resolve keyword '_post' into field. Choices are: id, name, slug
Because django request wrong table name.
(<Q: (AND: ('_post_tags_+__in', [<Post: (1)>, <Post: (2)>]))>,)
If I set related_name separately, this problem wouldn’t occur, but I can’t do that.
Is there any good way to solve this problem?
class Post:
tag1 = related.ManyToManyField(
Tag,
related_name='+',
)
tag2 = related.ManyToManyField(
Tag,
related_name='+',
)
...
class Tag:
...
for i in Post.objects.all().prefetch_related('tag1', 'tag2'):
i.tags.all()
=> error
for i in Post.objects.all().prefetch_related(Prefetch('tag1', Tag.objects.all()), Prefetch('tag2', Tag.objects.all())):
i.tag1.all()
=> error