model如下
class Publisher(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=50) website = models.URLField() class Author(models.Model): name = models.CharField(max_length=30) class AuthorDetail(models.Model): GENDER_CHOICE = ( (0, "男"), (1, "女"), ) sex = models.BooleanField(max_length=1, choices=GENDER_CHOICE) email = models.EmailField() birthday = models.DateField() author = models.OneToOneField(Author, on_delete=models.CASCADE) class Book(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE) publication_date = models.DateField()
>>> from hello.models import * >>> Author.objects.create(name="lilei") >>> AuthorDetail.objects.create(sex=False,email=‘13@qq.com‘, birthday="1989-08-20", author_id=1)
注意最后的author_id=1, 其中author_id是authordetail表中自动生成的字段名,1的值是通过在Author表中插入作者记录后自动生成的id号。
>>> Author.objects.all().values("id", ‘name‘) <QuerySet [{‘id‘: 1, ‘name‘: ‘lilei‘}, {‘id‘: 2, ‘name‘: ‘jack‘}]>
pub1 = Publisher() pub1.name = ‘电子工业出版社‘ pub1.address = ‘华阳‘ pub1.save()
Book.objects.create(title=‘小王子‘, publisher=pub1, publication_date=‘2009-05-06‘) #对象的方式 或者 Book.objects.create(title="小王子", publisher_id=2, publication_date="2009-08-12") #id的方式
book1=Book.objects.get(id=1) #首先根据书籍id号得到书籍的对象 author1 = Author.objects.get(id=1) #再根据作者id号得到作者的对象 book1.authors.add(author1)
author=Author.objects.get(id=1) author.name=‘jack‘ author.save()
原文:https://www.cnblogs.com/regit/p/12612322.html