#30976: ManyToManyField does not create JOIN when target object contains a
ForeignKey with the same name as the default related_query_name
-------------------------------------+-------------------------------------
Reporter: Ben Davis | Owner: nobody
Type: Bug | Status: new
Component: Database layer | Version: 2.2
(models, ORM) |
Severity: Normal | Resolution:
Keywords: | Triage Stage:
| Unreviewed
Has patch: 0 | Needs documentation: 0
Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 0 | UI/UX: 0
-------------------------------------+-------------------------------------
Description changed by Ben Davis:
Old description:
> Consider the following models. There is an `Entity` model which can be
> one of two types, a USER or a GROUP. There are `User` and `UserGroup`
> models that represent the sub-types, each having a `OneToOneField`
> pointing back to `Entity` (basically model inheritance w/o subclassing).
>
> An entity (which could be a user or a group) can exist another group (so,
> a user can belong to a group, and a group can also belong to a group)
>
> {{{
> #!python
> class Entity(models.Model):
> entity_id = models.AutoField(primary_key=True)
> name = models.CharField(max_length=128)
> type = models.CharField(max_length=32, choices=(
> ('USER', 'User'),
> ('USER_GROUP', 'User group')
> ))
> groups = models.ManyToManyField(
> 'UserGroup',
> through='UserGroupMember',
> through_fields=('member_entity', 'user_group')
> )
>
> class Meta:
> managed = False
> db_table = 'entity'
> unique_together = (('type', 'name'),)
>
> class User(models.Model):
> user_id = models.AutoField(primary_key=True)
> entity = models.OneToOneField(Entity, models.DO_NOTHING, unique=True)
> email = models.EmailField()
>
> class Meta:
> managed = False
> db_table = 'user'
>
> class UserGroup(models.Model):
> user_group_id = models.AutoField(primary_key=True)
> entity = models.OneToOneField(Entity, models.DO_NOTHING, unique=True,
> related_name='group')
> disabled = models.BooleanField()
>
> class Meta:
> managed = False
> db_table = 'user_group'
>
> def __str__(self):
> return self.entity.name
>
> class UserGroupMember(models.Model):
> user_group = models.ForeignKey(UserGroup, models.DO_NOTHING)
> member_entity = models.ForeignKey(Entity, models.DO_NOTHING)
>
> class Meta:
> managed = False
> db_table = 'user_group_member'
> unique_together = (('user_group', 'member_entity'),)
>
> def __str__(self):
> print(f'{self.user_group}->{self.member_entity}')
>
> }}}
>
> When I make the following query, it does not produce the expected join:
>
> {{{
> >>> entity = Entity.objects.get(pk=2)
> >>> print(entity.groups.all().query)
> SELECT "user_group"."user_group_id", "user_group"."entity_id",
> "user_group"."disabled" FROM "user_group" WHERE "user_group"."entity_id"
> = 2
> }}}
>
> This happens because the field accessor creates this implicit filter from
> the target model: `UserGroup.objects.filter(entity__entity_id=2)`. It
> assumes the default reverse name, which happens to conflict with the
> `entity` field on the target model.
>
> A workaround is to simply supply the `reverse_query_name` argument on the
> `ManyToManyField` with something other than `"entity"`. However, it took
> me quite a while to figure out what was happening here.
>
> Django already warns about conflicting reverse names. It seems that there
> should also be a warning for this case.
New description:
Consider the following models. There is an `Entity` model which can be one
of two types, a USER or a GROUP. There are `User` and `UserGroup` models
that represent the sub-types, each having a `OneToOneField` pointing back
to `Entity` (basically model inheritance w/o subclassing).
An entity (which could be a user or a group) can exist another group (so,
a user can belong to a group, and a group can also belong to a group)
{{{
#!python
class Entity(models.Model):
entity_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=128)
type = models.CharField(max_length=32, choices=(
('USER', 'User'),
('USER_GROUP', 'User group')
))
groups = models.ManyToManyField(
'UserGroup',
through='UserGroupMember',
through_fields=('member_entity', 'user_group')
)
class Meta:
managed = False
db_table = 'entity'
unique_together = (('type', 'name'),)
class User(models.Model):
user_id = models.AutoField(primary_key=True)
entity = models.OneToOneField(Entity, models.DO_NOTHING, unique=True)
email = models.EmailField()
class Meta:
managed = False
db_table = 'user'
class UserGroup(models.Model):
user_group_id = models.AutoField(primary_key=True)
entity = models.OneToOneField(Entity, models.DO_NOTHING, unique=True,
related_name='group')
disabled = models.BooleanField()
class Meta:
managed = False
db_table = 'user_group'
def __str__(self):
return self.entity.name
class UserGroupMember(models.Model):
user_group = models.ForeignKey(UserGroup, models.DO_NOTHING)
member_entity = models.ForeignKey(Entity, models.DO_NOTHING)
class Meta:
managed = False
db_table = 'user_group_member'
unique_together = (('user_group', 'member_entity'),)
def __str__(self):
print(f'{self.user_group}->{self.member_entity}')
}}}
When I make the following query, it does not produce the expected join:
{{{
>>> entity = Entity.objects.get(pk=2)
>>> print(entity.groups.all().query)
SELECT "user_group"."user_group_id", "user_group"."entity_id",
"user_group"."disabled" FROM "user_group" WHERE "user_group"."entity_id" =
2
}}}
This happens because the field accessor creates this implicit filter from
the target model: `UserGroup.objects.filter(entity__entity_id=2)`. It
assumes the default reverse name, which happens to conflict with the
`entity` field on the target model.
A workaround is to simply supply the `related_query_name` argument on the
`ManyToManyField` with something other than `"entity"`. However, it took
me quite a while to figure out what was happening here.
Django already warns about conflicting reverse relation names. It seems
that there should also be a warning for this case.
--
--
Ticket URL: <https://code.djangoproject.com/ticket/30976#comment:1>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-updates/068.22650ad2dd1e326592badadcf0eb9ae4%40djangoproject.com.