2

I want to create one model which has two manytomanyfield. I don't want Django to create two associations tables but the same association table for both manytomanyfield.

This is my model:

class Tab(WModel):
    forms = models.ManyToManyField('Form', null=True, blank=True)
    fields = models.ManyToManyField('Field', null=True, blank=True)
    number = models.IntegerField(null=True, blank=True)

    class Meta:
        db_table = 'tab'

I just want this association table to be created:

tab_assoc :
   id_tab
   id_form
   id_field
   number
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
  • Have you tried `through` parameter? https://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships – freakish Jun 11 '14 at 13:34
  • Yes, i already looked at through parameter but its not seems to be for this case. You know, i just want an association table references two models.. – djangopuccino Jun 11 '14 at 13:41

1 Answers1

2
class Field(models.Model):
    name = models.CharField(max_length=128)

    def __str__(self):              # __unicode__ on Python 2
        return self.name

class Form(models.Model):
    name = models.CharField(max_length=128)
    fields = models.ManyToManyField(Field, through='Tab')

    def __str__(self):              # __unicode__ on Python 2
        return self.name

class Tab(models.Model):
    field = models.ForeignKey(Field)
    form = models.ForeignKey(Form)
Asad Iqbal
  • 304
  • 4
  • 16
  • It doesnt work. I can save one object Tab, but When i trie to save the association "tab / form" in the Form object form, django gives this error : "AttributeError at /form/edit/2/ Cannot set values on a ManyToManyField which specifies an intermediary model. Use Tab's Manager instead." – djangopuccino Jun 11 '14 at 14:12
  • kindly look into this for understanding http://stackoverflow.com/questions/3091328/django-cannot-set-values-on-a-manytomanyfield-which-specifies-an-intermediary-mo Here telling how to save data in this case. – Asad Iqbal Jun 11 '14 at 14:38
  • save your model like this . tab = Tab(field = YOURFIELD,form=YOURFORM); tab.save() – Asad Iqbal Jun 11 '14 at 14:44