Login

ManyToManyField no syncdb

Author:
powerfox
Posted:
January 22, 2009
Language:
Python
Version:
1.0
Tags:
model field manytomany manytomanyfield syncdb
Score:
4 (after 4 ratings)

Sumary

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.

Example

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

More like this

  1. FieldAccessForm (per-field user access for forms derived from models) by Killarny 6 years, 10 months ago
  2. ModelForm Class saving m2m by ckarrie2 3 years, 10 months ago
  3. DefaultValueWidget by miracle2k 8 years, 1 month ago
  4. Link raw_id_fields (both ForeignKeys and ManyToManyFields) to their change pages by EmilStenstrom 4 years, 11 months ago
  5. Manager for something like __inall by apollo13 7 years, 9 months ago

Comments

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.