I have user profile model with M2M field
class Account(models.Model):
...
friends = models.ManyToManyField('self', symmetrical=True, blank=True)
...
Now I need to know HOW and WHEN add each other as a FRIEND
And I created a model for that
class Account(models.Model):
...
friends = models.ManyToManyField('self', symmetrical=False, blank=True, through="Relationship")
...
class Relationship(models.Model):
""" Friends """
from_account = models.ForeignKey(Account, related_name="relationship_set_from_account")
to_account = models.ForeignKey(Account, related_name="relationship_set_to_account")
# ... some special fields for friends relationship
class Meta:
db_table = "accounts_account_friends"
unique_together = ('from_account','to_account')
Should I create any migration for this changes or not ?
If you have any suggestions you are feel free write their here.
Thanks
PS: accounts_account table already contain records
First off, I’d avoid using the
db_tablealias if you can. This makes it harder to understand the table structure, as it is no longer in sync with the models.Secondly, the South API offers functions like
db.rename_table(), which can be used by manually editing the migration file. You can rename theaccounts_account_friendstable toaccounts_relation(as Django would name it by default), and add the additional columns.This combined gives you the following migration:
The unique relation is removed, and recreated so the constraint has the proper name.
The add column statements are easily generated with the following trick:
Relationshipmodel inmodels.pywith foreign key fields only, and no changes to the M2M field yet.Relationshipmodel../manage.py schemamigration app --auto --stdout | tee final-migration.py | grep columnThen you have everything you need to construct the migration file.