Django的quarySet
models.py 代码
1 from django.db import models 2 3 # Create your models here. 4 5 6 class Author(models.Model): 7 name = models.CharField(max_length=30) 8 qq = models.CharField(max_length=20) 9 add = models.CharField(max_length=50) 10 email = models.EmailField() 11 12 def __str__(self): 13 return self.name 14 15 16 class Article(models.Model): 17 title = models.CharField(max_length=50) 18 author = models.ForeignKey(Author, on_delete=models.CASCADE) 19 content = models.TextField() 20 score = models.IntegerField() 21 tags = models.ManyToManyField('Tag') 22 23 def __str__(self): 24 return self.title 25 26 27 class Tag(models.Model): 28 name = models.CharField(max_length=50) 29 30 def __str__(self): 31 return self.name
initdb.py代码
1 import random 2 from my_query.wsgi import * 3 from blog.models import Author, Article, Tag 4 import os,django 5 6 os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_query.settings") 7 django.setup() 8 9 author_name_list = ['dengyexun', 'lina', 'zhangming'] 10 article_title_list = ['Django book', 'Java book', 'C# book'] 11 12 13 def create_author(): 14 for author_name in author_name_list: 15 author, created = Author.objects.get_or_create(name=author_name) 16 author.qq = ''.join( 17 str(random.choice(range(10))) for i in range(9) 18 ) 19 author.add = 'addr_%s' % (random.randrange(1, 3)) 20 author.email = '%s@qq.com' % (author.add) 21 author.save() 22 23 24 def create_article_tag(): 25 for article_title in article_title_list: 26 tag_name = article_title.split(' ')[0] 27 tag, created = Tag.objects.get_or_create(name=tag_name) 28 random_author = random.choice(Author.objects.all()) 29 30 for i in range(1, 21): 31 title = '%s_%s' % (article_title, i) 32 article, created = Article.objects.get_or_create( 33 title=title, defaults={ 34 'author': random_author, 35 'content': '%s content' % title, 36 'score': random.randrange(70, 90), 37 } 38 ) 39 article.tags.add(tag) 40 41 42 def main(): 43 create_author() 44 create_article_tag() 45 46 47 if __name__ == '__main__': 48 main() 49 print('Done')
参考:
https://code.ziqiangxuetang.com/django/django-queryset-advance.html
时刻记着自己要成为什么样的人!