[django]Django外键(ForeignKey)操作以及related_name的作用

https://blog.csdn.net/hpu_yly_bj/article/details/78939748

加上


核心related_name作用

https://blog.csdn.net/lanyang123456/article/details/68962515

定义表Apple:

class Apple( models.Model):
    origin_level = models.ForeignKey(AppleLevel)
    new_level = models.ForeignKey(AppleLevel)

就会出现以下问题

monitor.apple: Accessor for field ‘origin_level’ clashes with related field ‘AppleLevel.apple_set’. Add a related_name argument to the definition for ‘origin_level’. 
monitor.apple: Accessor for field ‘new_level’ clashes with related field ‘AppleLevel.apple_set’. Add a related_name argument to the definition for ‘new_level’.

解决办法:

使用related_name属性定义名称(related_name是关联对象反向引用描述符)。 
具体修改代码如下:

class Apple( models.Model):
    origin_level = models.ForeignKey(AppleLevel, related_name='orgin_level_appleset')
    new_level = models.ForeignKey(AppleLevel, related_name='new_level_appleset')
posted @ 2018-08-27 14:41  mmaotai  阅读(700)  评论(0编辑  收藏  举报