Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'
like image 697
Pranayjeet Thakare Avatar asked Dec 11 '25 00:12

Pranayjeet Thakare


1 Answers

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.

like image 195
Jonathan Davis Avatar answered Dec 12 '25 14:12

Jonathan Davis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!