Hi everyone,
Posting a new thread here as the old one might be stale. The other post was about displaying something on the front-end, and this is more about the migrations.
I've read and followed these sources:
- https://dbslusser.medium.com/adding-a-through-table-to-existing-m2m-fields-3003d979444b
- https://docs.djangoproject.com/en/5.0/howto/writing-migrations/#changing-a-manytomanyfield-to-use-a-through-model
I have an existing many-to-many relationship in an app called stem:
class Collection(models.Model):
datasets = models.ManyToManyField(
Dataset,
through="CollectionDataset",
verbose_name='Datasets',
related_name='collections')
Django creates the table stem_collection_datasets automatically when I define a ManyToMany relationship this way. So this is now an existing table with existing records that holds these relationships.
Now I want to add an additional field to this relationship, order, so that I could order the m2m relationships. To do this, I have to actually create a through table myself and specify this new field. So I can no longer use the through table that Django created automatically:
class Collection(models.Model):
datasets = models.ManyToManyField(
Dataset,
verbose_name='Datasets',
related_name='collections')
class CollectionDataset(models.Model):
class Meta:
ordering = ('order',)
auto_created = True
unique_together = ['dataset', 'collection']
dataset = models.ForeignKey(Dataset, on_delete=models.CASCADE)
collection = models.ForeignKey(Collection, on_delete=models.CASCADE)
order = models.PositiveIntegerField(null=True, blank=True, default=0)
The instructions linked above indicated that if I just create a new through table manually, then create a migration, it will delete the old through table and I will lose the existing relationships. After following all of the instructions, I've ended up with two migration scripts. I'll post them as a comment because I'm out of characters for the initial post.