Django 解決model 反向引用中的related_name問題
問題:
定義表Apple:
class Apple( models.Model): origin_level = models.ForeignKey(AppleLevel) new_level = models.ForeignKey(AppleLevel)
出現(xiàn)如下問題:
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’.
原因:
一個(gè)數(shù)據(jù)表同時(shí)兩次外鍵引用另一個(gè)表,出現(xiàn)重名問題。
解決辦法:
使用related_name屬性定義名稱(related_name是關(guān)聯(lián)對(duì)象反向引用描述符)。
具體修改代碼如下:
class Apple( models.Model): origin_level = models.ForeignKey(AppleLevel, related_name=’orgin_level_appleset’) new_level = models.ForeignKey(AppleLevel, related_name=’new_level_appleset’)
related_name使用之后,有什么用處呢?
用處就是:
通過AppleLevel可以得到引用自身的Apple對(duì)象。
例如,
通過origin_level引用AppleLevel 中id為12的Apple的所有對(duì)象
AppleLevel.object.get(id=12).origin_level_appleset.objects.all()
通過new_level引用AppleLevel 中id為12的Apple的所有對(duì)象
AppleLevel.object.get(id=12).new_level_appleset.objects.all()
以上這篇Django 解決model 反向引用中的related_name問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. ASP動(dòng)態(tài)網(wǎng)頁制作技術(shù)經(jīng)驗(yàn)分享2. ASP中實(shí)現(xiàn)字符部位類似.NET里String對(duì)象的PadLeft和PadRight函數(shù)3. 解析原生JS getComputedStyle4. CSS可以做的幾個(gè)令你嘆為觀止的實(shí)例分享5. ASP實(shí)現(xiàn)加法驗(yàn)證碼6. 利用CSS3新特性創(chuàng)建透明邊框三角7. 淺談?dòng)蓀osition屬性引申的css進(jìn)階討論8. vue前端RSA加密java后端解密的方法實(shí)現(xiàn)9. php使用正則驗(yàn)證密碼字段的復(fù)雜強(qiáng)度原理詳細(xì)講解 原創(chuàng)10. JSP+Servlet實(shí)現(xiàn)文件上傳到服務(wù)器功能

網(wǎng)公網(wǎng)安備