publish表数据
app01/models.py
from django.db import modelsclass Publish(models.Model): nid = models.AutoField(primary_key=True) name=models.CharField( max_length=32) city=models.CharField( max_length=32) email=models.EmailField() def __str__(self): return self.name class Book(models.Model): nid = models.AutoField(primary_key=True,verbose_name=" 编号") #定义在admin中显示中文名称“编号” title = models.CharField( max_length=32,verbose_name="书籍名称") publishDate=models.DateField() price=models.DecimalField(max_digits=5,decimal_places=2) # 与Publish建立一对多的关系,外键字段建立在多的一方 publish=models.ForeignKey(to="Publish",to_field="nid",on_delete=models.CASCADE) # 与Author表建立多对多的关系,ManyToManyField可以建在两个模型中的任意一个,自动创建第三张表 authors=models.ManyToManyField(to='Author',) def __str__(self): return self.title
app01/views.py
from django.shortcuts import render,HttpResponse from app01.models import * def test(request): # 由一个模型拿它的名字、app的名字、字段对象以及字段对象中的属性 #拿模型名称 model_name = Book._meta.model_name print(model_name,type(model_name)) # book <class 'str'> #拿模型的app名称 app_label = Book._meta.app_label print(app_label,type(app_label)) # app01 <class 'str'> # 拿模型的字段对象 title = Book._meta.get_field("title") print(title,type(title)) # app01.Book.title <class 'django.db.models.fields.CharField'> max_length = title.max_length print(max_length,type(max_length)) # 32 <class 'int'> # 获取字段中定义的名称(可中文或英文) var = title.verbose_name print(var,type(var)) # 书籍名称 <class 'str'> #-------------------------------------------------------------------------------------------- #由字段的字符串名称“publish”取字段对象、该字段的模型表名称、该字段相关联的模型、 # 以及该字段相关联模型表的所有数据 #取字段对象 publish = Book._meta.get_field("publish") print(publish,type(publish)) #app01.Book.publish <class 'django.db.models.fields.related.ForeignKey'> #取该字段模型表 publish_model_name=publish.rel print(publish_model_name,type(publish_model_name)) #<ManyToOneRel: app01.book> <class 'django.db.models.fields.reverse_related.ManyToOneRel'> # 取该字段相关联模型表 publish_relate_model_name=publish.rel.to print(publish_relate_model_name,type(publish_relate_model_name)) #<class 'app01.models.Publish'> <class 'django.db.models.base.ModelBase'> #取该字段相关联模型表的所有数据 data_list=publish.rel.to.objects.all() print(data_list,type(data_list)) #<QuerySet [<Publish: 苹果出版社>, <Publish: 光子出版社>]> <class 'django.db.models.query.QuerySet'> return HttpResponse("OK")