简体   繁体   中英

How to get all objects of a Parent model of which foreign key exist in child model in Django?

I have 2 models

#models
class Parent(models.Model):
     name = models.CharField()

class Child(models.Model)
     parentLink = models.ForeignKey(Parent)
     timeStamp = models.DateTimeField(auto_now_add=True)

I want all the objects of Parent model having foreign key mentioned in Child model and some filter on timeStamp field.

How do I do this reverse fetching of objects?

It's MySQL would be something like this

SELECT Parent.name FROM Parent JOIN Child on Parent.Id = Child.parentLink WHERE Child.timeStamp > '2016-01-01 : 00.00.00'

If I understand what you need correctly, it should be something like this:

Parent.objects.filter(
    child__isnull=False,
    child__timeStamp__gt=datetime.strptime(
        '2016-01-01 00.00.00',
        '%Y-%m-%d %H.%M.%S'
    )
)

This fetches all Parent objects for which there is a child whose timestamp is later than 2016/01/01.

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