Search code examples
pythonmysqldjangodjango-modelsforeign-key-relationship

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'

Solution

  • 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.