代码如下:
class User(models.Model): username = models.CharField(max_length=20) password = models.CharField(max_length=100)
class Category(models.Model): """文章分类表""" name = models.CharField(max_length=100) class Article(models.Model): """文章表""" title = models.CharField(max_length=100,null=True) content = models.TextField() category = models.ForeignKey("Category",on_delete=models.CASCADE) author = models.ForeignKey("User",on_delete=models.CASCADE)
获取文章标题中包含"hello"的所有的分类:
categories = Category.object.filter(article__title__contains("hello"))
在每个对象中都添加一个author__name
的字段,用来显示这个文章的作者的年龄
articles = Article.objects.annotate(author_name=F("author__name"))