mysql与django中的外键

django外键包括OneToOneField,ForeignKey,ManyToManyField,使用可以与其他Model形成联系,互相调用,十分强大。最近在学习使用mysql数据库,发现mysql对django的外键有独特的表示方法。

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。
####首先是一对一关系
![](http://upload-images.jianshu.io/upload_images/2222847-c31132baeac74d72.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
author中belong_to字段变为belong_to_id字段,与auth_user的id相对应。
####多对一

![](http://upload-images.jianshu.io/upload_images/2222847-9e767def355a157d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
与一对一差不多,也是通过id与其作者相关联
####多对多

![
![](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关联,而是建立了一张新的表来表示其关系。

了解mysql中对应的表示方法,通过调用id,就可以得到想要的数据
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容