- 关于related_name的讲解ManyToMany,ForeginKey
- 当一张表中外键指向同一个表的字段数大于等于2时,就得使用related_name,在最近的几次学习中发现,
- related_name没有想象中那么简单,原本以为只是用于区分(不好好看文档的结果),结果在一次使用formsets
- 的过程中发现了问题,不管添加了多少子表单,form-TOTAL_FORMS恒不变, prefix后面跟的值永远是NAN,
- 细心的话就能发现firebug内显示的prefix与自己定义的明显不同,最后在主管的帮助下,问题渐渐明了,我在外键
- 内定义了related_name,该项就是firebug内显示的prefix,之后在使用反向查询时又出了问题,在Django Doc
- 里其实有句话说明了这个问题,
- http://docs.djangoproject.com/en/dev/topics/db/queries/#many-to-many-relationships
- Like ForeignKey, ManyToManyField can specify related_name. In the above example, if the ManyToManyField
- in Entry had specified related_name='entries', then each Author instance would have an entries attribute
- instead of entry_set.
- 当定义了related_name后”_set”这类查询就被related_name代替了,所以用”_set”会报错。