当前位置 : 主页 > 编程语言 > python >

Django多对多模型

来源:互联网 收集:自由互联 发布时间:2022-06-15
models.pyfrom django.db import models class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() class Author(models.Model): name = models.CharField(max_length=50) email = models.EmailField() class Entry(

models.pyfrom django.db import models


class Blog(models.Model):
name = models.CharField(max_length=100)
tagline = models.TextField()



class Author(models.Model):
name = models.CharField(max_length=50)
email = models.EmailField()



class Entry(models.Model):
blog = models.ForeignKey(Blog)
headline = models.CharField(max_length=255)
body_text = models.TextField()
pub_date = models.DateField()
mod_date = models.DateField()
authors = models.ManyToManyField(Author)
n_comments = models.IntegerField()
n_pingbacks = models.IntegerField()
rating = models.IntegerField()

views.py##############多对多##############

#正向操作
# obj = models.Entry.objects.get(id=1)
# print(obj,obj.headline,obj.authors)
# print(obj.authors.all())
# author1 = models.Author.objects.filter(id__gt=2)
# author1 = models.Author.objects.filter(id=2)
# print(author1)
# obj.authors.add(*author1)

#反向操作 _set关键字
# author1 = models.Author.objects.get(id=2)
# author1.entry_set.add(*models.Entry.objects.filter(id=1))
# print(author1,author1.name,entry1)



#_set 关联表相关操作
# author1 = models.Author.objects.get(id=1)
# author1.entry_set.add(*models.Entry.objects.filter(id=1))
#删除关联表信息
# author1.entry_set.remove(*models.Entry.objects.filter(id=1))
#修改关联表 清空所有再增加数据 默认clear=False 如果数据存在 不做修改
# author1.entry_set.set(models.Entry.objects.filter(id__gt=1))
# author1.entry_set.set(models.Entry.objects.filter(id=2))
#默认clear=True 则清楚所有 再添加
# author1.entry_set.set(models.Entry.objects.filter(id=2),clear=True)
#delete() 慎用 删除关联表中与author1 id=1相关的 并且 删除另外一个字段关联的表entry的数据
# author1.entry_set.all().delete()
#create , get_or_create ,update_or_create
# author1.entry_set.get_or_create(body_text='h33333')

总结:


其他:




上一篇:Python--爬虫数据解析
下一篇:没有了
网友评论