简体   繁体   中英

how to query from parent model to child model

I want to get all the posts created today but instead of querying from post model I want to query from the Author model. I tried this but it didn't work

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')

You can filter anyauthor name like this ok or u can query this

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

From the above query u can filter using reverse relationship

query = Author.objects.all()

It will gives you all author name

query = Post.objects.all()

It will gives you all Post name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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