Saqib Ali
Saqib Ali

Reputation: 12585

How can I follow a Django reverse-foreign-key and then another reverse-foreign-key?

Suppose I have 3 Django models:

mymodela/models.py:

class MyModelA(models.Model):
    my_int = models.IntegerField()
    created_ts = models.DateTimeField()

mymodelb/models.py:

from mymodela.models import mymodela
class MyModelB(models.Model):
    my_int = models.IntegerField()
    my_a = models.ForeignKey(MyModelA, related_name="MyModelB_a")
    created_ts = models.DateTimeField()

mymodelc/models.py:

from mymodelb.models import MyModelB
class MyModelC(models.Model):
    my_int = models.IntegerField()
    my_b = models.ForeignKey(MyModelB, related_name="MyModelC_b")
    created_ts = models.DateTimeField()

I have an instance of MyModelA called a. I would like to calculate this QuerySet:

MyModelC.objects.filter(my_b__my_a=a).latest("created_ts")

However, I need to calculate this queryset from within a method of a. And since MyModelA doesn't import MyModelC, I cannot do that directly. I need to follow the reverse links. But how can I follow the reverse links twice to get what I need?

Upvotes: 1

Views: 429

Answers (1)

solarissmoke
solarissmoke

Reputation: 31454

In your mymodela/models.py (by the way, I'm not sure why you have separated all your models into separate directories like this - unless this is deliberate you might consider putting them all in your app's models.py file):

class MyModelA(models.Model):
    my_int = models.IntegerField()
    created_ts = models.DateTimeField()

    # A method that will fetch the most recent related MyModelC 
    def get_latest_c(self):
        from mymodelc.models import MyModelC
        return MyModelC.objects.filter(my_b__my_a=self).latest("created_ts")

Now when you have some instance of MyModelA called a, you call a.get_latest_c() to get the most recent related MyModelC object.

Upvotes: 1

Related Questions