'Join django unrelated models

I have 3 models and I'd like to join them and query in just one query. However, 2 of them do not have foreign keys to each other so I can't use the select_related() option.

Could I please request your help? Thanks

Here is the model schema:

class UserGroup(models.Model):
    group_name = models.CharField(max_length=80)
    user_id = models.CharField(max_length=20)

class StrategyUserGroupRel(models.Model):
    strategy = models.ForeignKey(Strategy, on_delete=models.PROTECT)
    user_group = models.ForeignKey(UserGroup, on_delete=models.PROTECT, to_field='group_name')


class SignalStrategyRel(models.Model):
    signal = models.ForeignKey(Signal, on_delete=PROTECT)
    strategy = models.ForeignKey(Strategy, on_delete=PROTECT)
  • My entry point would be "user_id"
  • First, I want to get all "group_name" linked to that "user_id".
  • Then, I want the "strategy" which the "group_name" is linked to (can be multiple strategies)
  • Finally, I want the "signal" which the "strategy" is linked to (can be multiple signals)

In SQL, it would be like this:

select * from strategy_user_group_rel sugr 
    inner join user_group ug 
    on sugr.user_group = ug.group_name 
       inner join signal_strategy_rel ssr
       on ssr.strategy_id = sugr.strategy_id
    where ug.user_id = "test_user"


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source