Clear with a M2M field with a through model
|Reported by:||anonymous||Owned by:||nobody|
|Component:||Database layer (models, ORM)||Version:||1.4|
|Has patch:||yes||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
This ticket deals with similar issues as #15161.
When you have a M2M field with a through model where one of the foreign keys uses a to_field, the to_field is ignored by add, remove and clear. Only clear is available when using a normal through but it would be nice to fix for all of them.
To see the currently wrong behavior try something like this:
class Through(models.Model): ffrom = models.ForeignKey('Two', to_field='slug') to = models.ForeignKey('One') class One(models.Model): name = models.CharField(max_length=100) class Two(models.Model): slug = models.CharField(max_length=24, unique=True) ones = models.ManyToManyField(One, through=Through) o = One(name='test') t = Two(slug='test2') Through(ffrom=t, to=o).save() t.ones.clear()
You'll see the relationship not being cleared as the queries use the value for the pk of t instead of the value of 'slug' on t ('test2').
The fix could be as simple as changing ManyRelatedManager._pk_val to not be pk value but to lookup the correct value for the field. (line 534)
Change History (19)
comment:3 Changed 5 years ago by
|Severity:||Normal → Release blocker|
|Triage Stage:||Unreviewed → Accepted|