Home > Net >  filtering before joining django orm
filtering before joining django orm

Time:07-28

I have three imaginary models:

 class Singer(BaseModel):
    singer_name = models.CharField(max_length=50, db_index=True)
    album  = ForeignKey(album, on_delete=models.CASCADE, null=True,
                         related_name="singer_album")

 class Album(BaseModel):
    album_name = models.CharField(max_length=50, db_index=True) 

 class Fan(BaseModel):
    fan_name = models.CharField(max_length=50, db_index=True) 
    admired_singer = ForeignKey(Singer, on_delete=models.CASCADE, null=True,
                         related_name="fan_singer")

now lets say I want to query all singers albums starting with 'g' that belong to the singer that the fan 'RSNboim' admired.

my intuition is to go like

queryset = Fan.objects.values('admired_singer','album_name').filter(fan_name = 'RSNboim', album_name__startswith='g')

and now is my primary Question

my real DB is running on about 6M records so I wish I could force Django to filter before it executes the join statement because it's consuming more effort first to join and only then filter by criteria.

will inserting the filter() before the values() actually execute filtering before joining? or does Django/Postgres have their own way of prioritizing the operation's order?

CodePudding user response:

You can call filter(), order_by(), etc. after the values() call, that means that these two calls are identical:

Blog.objects.values().order_by('id')
Blog.objects.order_by('id').values()

This is stated in the official django doc. Since this is a chrome link, I am unable to embed it.

https://docs.djangoproject.com/en/4.0/ref/models/querysets/#:~:text=Finally, note that you,).values()

Open the link in chrome, to go to the highlighted section or you can search the text I posted in the django site.

  • Related