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 (17)
comment:1 Changed 3 years ago by anonymous
- Needs documentation unset
- Needs tests unset
- Patch needs improvement unset
comment:3 Changed 3 years ago by russellm
- Severity changed from Normal to Release blocker
- Triage Stage changed from Unreviewed to Accepted
comment:11 Changed 2 years ago by Anssi Kääriäinen <akaariai@…>
- Resolution set to fixed
- Status changed from new to closed