'Django - Is it possible to get objects of "indirectly related one to one field" with reverse_many_to_one_manager?
For instance I have these models:
class Company(models.Model):
name = models.CharField(max_length=100)
class User(AbstractBaseUser):
email = models.EmailField(max_length=250, unique=True)
date_joined = models.DateTimeField(auto_now_add=True)
last_login = models.DateTimeField(auto_now=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
company = models.ForeignKey(Company, on_delete=models.PROTECT)
is_admin = models.BooleanField(default=False)
Now I can easily get all the profiles for a company using the following query:
Company.objects.first().profile_set.all()
But is there a way I can get the related users from company instead of profile, keeping in mind that a user object is one to one related with profile object?
Note: These models are just example models, and keeping in view the application logic, we can't combine user and profile model.
Solution 1:[1]
company = Company.objects.get(id=X)
User.objects.filter(profile__company=company)
or create a manager on Users:
def from_company(self, company: Company):
return self.filter(profile__company=company)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Luid Duarte |
