models.py 代码
from django.db import models # Create your models here. class Author(models.Model):
name = models.CharField(max_length=30)
qq = models.CharField(max_length=20)
add = models.CharField(max_length=50)
email = models.EmailField() def __str__(self):
return self.name class Article(models.Model):
title = models.CharField(max_length=50)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
content = models.TextField()
score = models.IntegerField()
tags = models.ManyToManyField('Tag') def __str__(self):
return self.title class Tag(models.Model):
name = models.CharField(max_length=50) def __str__(self):
return self.name
initdb.py代码
import random
from my_query.wsgi import *
from blog.models import Author, Article, Tag
import os,django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_query.settings")
django.setup() author_name_list = ['dengyexun', 'lina', 'zhangming']
article_title_list = ['Django book', 'Java book', 'C# book'] def create_author():
for author_name in author_name_list:
author, created = Author.objects.get_or_create(name=author_name)
author.qq = ''.join(
str(random.choice(range(10))) for i in range(9)
)
author.add = 'addr_%s' % (random.randrange(1, 3))
author.email = '%s@qq.com' % (author.add)
author.save() def create_article_tag():
for article_title in article_title_list:
tag_name = article_title.split(' ')[0]
tag, created = Tag.objects.get_or_create(name=tag_name)
random_author = random.choice(Author.objects.all()) for i in range(1, 21):
title = '%s_%s' % (article_title, i)
article, created = Article.objects.get_or_create(
title=title, defaults={
'author': random_author,
'content': '%s content' % title,
'score': random.randrange(70, 90),
}
)
article.tags.add(tag) def main():
create_author()
create_article_tag() if __name__ == '__main__':
main()
print('Done')
参考:
https://code.ziqiangxuetang.com/django/django-queryset-advance.html