对于ForeignKey外键,在开发中用的非常多,下边详细的记录下使用外键一对多时的操作。
1、比如下边,作者可以对应多篇文章,在文章Article模型中,定义一个外键,引用上边Author模型 ;当然你也可以在初始化的时候,为Author模型添加主键,下边Article文章模型外键默认引用Author模型主键为1的对象。这次我使用另外一种方式。
# 一对多关系 文章与作者就是典型的一对多的关系
class Author(models.Model):
username = models.CharField(max_length=20)
password = models.CharField(max_length=20)
class Article(models.Model):
author = models.ForeignKey('Author',on_delete=models.CASCADE)
title = models.CharField(max_length=20)
content = models.TextField()
上边创建完两个模型之后,先映射到数据库:
python manage.py makemigrations
python manage.py migrate
2、在视图函数中,为Author和Article两个模型添加数据, 之所以author.save( ) ,因为你必须事先保存Author模型的数据,下边
premary_k = Author.objects.get(pk=1) 才能有值,article.author = premary_k 才能知道外键引用的是 Author类中的哪一个对象。其实这个操作与初始化时,为Author模型添加主键,下边Article文章模型外键默认引用Author模型主键为1的对象是一样的。。。
# 检查数据库是否有同名的username
def check_username(username):
qs = Author.objects.filter(username=username)
return qs
# 添加文章和作者
def add_artical(request):
result = request.body
result_dict = json.loads(result.decode()) # 解析前端发来的数据
try:
username = result_dict['username']
password = result_dict['password']
title = result_dict['title']
content = result_dict['content']
if check_username(username): # 检查username是已经存在
return HttpResponseBadRequest('已经有username') # 如果数据库有同名账号,返回400
author = Author(username=username,password=password)
author.save()
article = Article(title=title,content=content)
premary_k = Author.objects.get(pk=1) # 取主键为1的对象
article.author = premary_k # author的外键是Author模型中主键为1的对象
article.save()
except Exception as e:
return HttpResponseBadRequest("数据不是json或不是有效字段")
return JsonResponse({'name':'success'})
使用postman发送数据
3、获得某个username下的所有文章
有2中方法,
1、方法一:使用属性 xxx_set 查看
看下:
使用属性xxx_set ,前边的xxx是使用外键ForeignKey的字段对应的 类的名字(Django会把类的名字转化成小写),以上边为例,定义了Author类和Article类,查看Author下某对象对应的所有文章:
查看主键为1的字段下的所有文章:
from .models import Author,Article
def view_articles():
CONST= []
author = Author.objects.get(pk=1)
articles = author.article_set.all() # 查看主键为1的对象下的所有文章
for item in articles:
qs_dict = {'title':item.title,'content':item.content}
CONST.append(qs_dict)
return CONST
# [{'title': '我和我的祖国', 'content': '我爱我的祖国'}, {'title': '明天会更好', 'content': '轻轻敲醒沉睡···'}]
2、方法二:在ForeignKey的参数中,定义一个related_name = xxx,xxx是自定义的名字,取值的时候:author.xxx.all()
author = Author.objects.get(pk=1)
articles = author.article.all() # 直接写在related_name = 'article'等号后边的名字即可
class Article(models.Model):
author = models.ForeignKey('Author',on_delete=models.CASCADE,related_name='article')
title = models.CharField(max_length=20)
content = models.TextField()