开发者

Django Show M2M field in either model when using forms.ModelForm

I am using the forms.ModelForm to create my form. I want to be able to show the manytomany field in both model开发者_开发技巧 forms, how do I do this?

If the manytomany relationship is defined in the model it is fine and just appears but if it is not in the model (but is still linked via the other model) it does not appear. How can I make it show up?

Hope this makes sense.

Thanks


Use this third party model field class. It's a four-liner that subclasses the regular ManyToMany class, but instructs Django not to create a separate table for the second relationship.

You create the relationship on the first model normally, explicitly specifying database table name ("db_table" option):

class FirstModel(models.Model):
    second_model = ManyToManyField('SecondModel', related_name='second_model', db_table=u'TABLE_FOR_FIRST_AND_SECOND_MODEL')
    ...

And for the second model use ManyToManyField_NoSyncdb, so it doesn't try to create a second table:

class SecondModel(models.Model):
    first_model = ManyToManyField_NoSyncdb('FirstModel', related_name='first_model', db_table=u'TABLE_FOR_FIRST_AND_SECOND_MODEL')
    ...

For more information refer to the right-hand description on django snippets.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜