django two manytomanyfield one association table

时间:2014-06-11 13:28:27

标签: python django postgresql-9.1 manytomanyfield

我想创建一个有两个很多地方的模型。我没有'希望django为manytomanyfield创建两个关联表,但是同一个关联表。

这是我的模特:

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'

我只想创建这个关联表:

tab_assoc :
   id_tab
   id_form
   id_field
   number

感谢您的回答

1 个答案:

答案 0 :(得分: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)