繁体   English   中英

如何从父 model 查询到子 model

[英]how to query from parent model to child model

我想获取今天创建的所有帖子,而不是从帖子 model 查询,我想从作者 model 查询。我试过了,但没有用

Author.objects.filter(post__created__date=date.today())
class Author(models.Model): #parent model
    name = models.CharField(max_length=200)

class Post(models.Model): #child model
    title= models.CharField(max_length=200)
    description = models.TextField()
    author= models.ForeignKey(Author,on_delete=models.CASCADE)
    created = DateTimeField(auto_created=True)
query = Post.objects.filter(author__name = 'anyauthername')


query = Post.objects.filter(author__name__startswith = 'startig words of author')

您可以像这样过滤任何作者姓名,或者您可以查询

query = Author.objects.filter(post__title = 'Postname')

从上面的查询中,您可以使用反向关系进行过滤

query = Author.objects.all()

它会给你所有的作者姓名

query = Post.objects.all()

它会给你所有的帖子名称

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM