ManyToManyField no syncdb

January 22, 2009
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', 
class Group(models.Model):
    users = ManyToManyField_NoSyncdb(User, related_name='users',
class ManyToManyField_NoSyncdb(models.ManyToManyField):
    def __init__(self, *args, **kwargs):
        super(ManyToManyField_NoSyncdb, self).__init__(*args, **kwargs)
        self.creates_table = False

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 4 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 4 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 11 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 12 months ago
  5. Help text hyperlinks by sa2812 1 year ago


dkg (on February 3, 2010):

Thanks, this was very useful to me, because i have m2m relationships that i want to look at from both directions.

In fact, it seems useful enough that it might be handy to have a creates_table argument to the built-in ManyToManyField (defaults to True), so this workaround wouldn't be necessary.


volman_jeff (on February 2, 2011):

Warning! This snippet fails in Django 1.2.3 since the Field property "creates_table" appears to no longer be supported. It tries to create the table which generates a "duplicate table" error.


Please login first before commenting.