- January 22, 2009
- model field manytomany manytomanyfield syncdb
- 4 (after 4 ratings)
M2M relation without creating table. Normally you should specify m2m only in one model, thus widgets for many-to-many relations will be displayed inline on whichever model contains the actual reference to the ManyToManyField. But if you want to be able to have widgets displayed on both form you need some tricks, for example using intermediary-models can help, but you will not get multiselect widget (and in case of inlining extra = multi). Also you can write your own form which takes care about adding widget (just 1 line) and setting default values and saving it (more than few lines of code). If you try ManyToManyField with same db_table specified, the only problem will be in syncdb (it will try to create two identical tables) and the only thing our class does is preventing creation of table for M2M, so in one model you should use ManyToManyField and in another ManyToManyField_NoSyncdb with the same db_table argument.
So to have M2M widgets in both forms you can write:
class User(models.Model): #... groups = ManyToManyField('Group', related_name='groups', db_table=u'USERS_TO_GROUPS') class Group(models.Model): #... users = ManyToManyField_NoSyncdb(User, related_name='users', db_table=u'USERS_TO_GROUPS')
1 2 3 4
class ManyToManyField_NoSyncdb(models.ManyToManyField): def __init__(self, *args, **kwargs): super(ManyToManyField_NoSyncdb, self).__init__(*args, **kwargs) self.creates_table = False