mysql與django中的外鍵

django外鍵包括OneToOneField,F(xiàn)oreignKey,ManyToManyField,使用可以與其他Model形成聯(lián)系,互相調(diào)用,十分強(qiáng)大。最近在學(xué)習(xí)使用mysql數(shù)據(jù)庫,發(fā)現(xiàn)mysql對django的外鍵有獨(dú)特的表示方法。

from django.db import models
from django.contrib.auth.models import User
class Author(models.Model):
    belong_to = models.OneToOneField(to=User, related_name='profile')
    name = models.CharField(max_length=20)
    def __str__(self):
        return self.name
class Book(models.Model):
    belong_to = models.ForeignKey(to=Author, related_name='book') 
   name = models.CharField(max_length=50)
    content = models.TextField()
    def __str__(self):
        return self.name
class Tag(models.Model):
    book = models.ManyToManyField(to=Book, related_name='tags')
    name = models.CharField(max_length=10)
    def __str__(self):
        return self.name```
為了方便表示,簡單的建了這些Model。
####首先是一對一關(guān)系
![](http://upload-images.jianshu.io/upload_images/2222847-c31132baeac74d72.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
author中belong_to字段變?yōu)閎elong_to_id字段,與auth_user的id相對應(yīng)。
####多對一

![](http://upload-images.jianshu.io/upload_images/2222847-9e767def355a157d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
與一對一差不多,也是通過id與其作者相關(guān)聯(lián)
####多對多

![
![](http://upload-images.jianshu.io/upload_images/2222847-2bfc7f5feec90508.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
](http://upload-images.jianshu.io/upload_images/2222847-e667bca048535c71.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
這種最為特殊,自身表中沒有與book關(guān)聯(lián),而是建立了一張新的表來表示其關(guān)系。

了解mysql中對應(yīng)的表示方法,通過調(diào)用id,就可以得到想要的數(shù)據(jù)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容