外键
外键是数据表用来指向某个外来的键值的字段
1.外键的作用:
1.去除冗余的数据
2.数据结构化,使用和执行效率更高
3.便于管理,更好地存储数据.
总结:重复的数据,不同类型的内容
2.ForeignKey
from django.db import models
class SchoolClass(models.Model):
class_name = models.CharField(max_length=32)
class_master = models.CharField(max_length=32)
def __str__(self):
return self.class_name
class Student(models.Model):
name = models.CharField(max_length=32)
SEX_CHOICE = {
(0, "男"),
(1, "女")
}
sex = models.IntegerField(choices=SEX_CHOICE, default=0)
student_class = models.ForeignKey(to="SchoolClass", on_delete=models.CASCADE)
def __str__(self):
return self.name
3.ManyToMantField
from django.db import models
class Author(models.Model):
author_name = models.CharField(max_length=24)
def __str__(self):
return '<Author: {0}>'.format(self.author_name)
__unicode__ = __str__
class Book(models.Model):
book_name = models.CharField(max_length=48)
authors = models.ManyToManyField(Author)
def __str__(self):
return '<Book: {0}>'.format(self.book_name)
__unicode__ = __str__
4.OneToOneField
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
nickname = models.CharField(max_length=24)
def __str__(self):
return '<Profile: {0}>'.format(self.nickname)
__unicode__ = __str__
5.ContentType
from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
class Article(models.Model):
title = models.CharField(max_length=36)
content = models.TextField(blank=True)
def __str__(self):
return '<Article: {0}>'.format(self.title)
__unicode__ = __str__
class Video(models.Model):
video_name = models.CharField(max_length=36)
url = models.URLField()
def __str__(self):
return '<Video: {0}>'.format(self.video_name)
__unicode__ = __str__
class Comment(models.Model):
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
text = models.TextField()
def __str__(self):
return '<Comment: {0}>'.format(self.text)
__unicode__ = __str__
'''
comment = Comment.objects.first()
obj = comment.content_object # 直接得到所被评论的对象
'''
'''
from django.contrib.contenttypes.models import ContentType
article = Article.objects.first()
article_content_type = ContentType.objects.get_for_model(article)
# 通过Comment自身的筛选查询得到
comments = Comment.objects.filter(content_type=article_content_type, object_id=article.pk)
'''
'''
from django.contrib.contenttypes.fields import GenericRelation
# 对应模型加入 comments = GenericRelation('Comment') 字段
article = Article.objects.first()
comments = article.comments.all()
'''
转载请注明原文地址:https://ipadbbs.8miu.com/read-27737.html