Issue
I was wondering what is the most django correct way of fetching the instance in an OneToOneField
, when the instance I'm fetching from is accessed through a ManyToManyRelatedManager
?
Specifically, I have a CustomGroup
model that has a OneToOneField
to auth.Group
. Then I want to fetch each CustomGroup
instance from the user instance, through the groups
manager.
These are my models:
from django.contrib.auth.models import AbstractUser, Group
from django.db import models
class CustomGroup(models.Model):
group = models.OneToOneField(Group, on_delete=models.CASCADE, related_name="custom_group")
class CustomUser(AbstractUser):
# my custom fields
I would like to have a get_custom_groups
method on the CustomUser
model that returns a RelatedManager
with the base queryset as all the CustomGroup
that this user is related to (much like user.groups
, but only with CustomGroup
as the model).
What I have usually done is something like this:
def get_custom_groups(self):
custom_group_ids = self.groups.all().values_list("custom_group", flat=True)
return CustromGroup.objects.filter(id__in=custom_group_ids)
Is this the best way of doing this, or is there another, smarter way?
Solution
Is this the best way of doing this, or is there another, smarter way?
No, there is no need to first fetch the custom_group
items, etc. We can filter directly with:
def get_custom_groups(self):
return CustromGroup.objects.filter(group__user=self)
Answered By - willeM_ Van Onsem
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.