class FutsalUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(verbose_name='email address', max_length=255, unique=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(
_('staff status'),
default=True,
help_text=_('Designates whether the user can log into this admin site.'),
)
objects = FutsalUserManager()
USERNAME_FIELD = 'email'
def __str__(self):
return self.email
@property
def company_details(self):
company_data = Company.objects.filter(user= self)
if company_data :
company_data.name
return company_data
else:
return None
class Company(TimeStampedModel):
name = models.CharField(max_length=200)
hr_name = models.CharField(max_length=200)
hr_email = models.CharField(max_length=200)
user = models.ForeignKey(
settings.AUTH_USER_MODEL, models.DO_NOTHING)
hr_verified = models.BooleanField(default=False, blank=True)
primary_phone = models.CharField(null=True, max_length=200)
followed_by = models.CharField(max_length=200,default="Not assigned")
comments = models.TextField(default="")
def __str__(self):
return self.name
CodePudding user response:
1. There is no need to create a custom function in Model, to fetch other values of other table which are in relation.
[ 1 ] you should have a related_name
in your company user table. like
user = models.ForeignKey(
settings.AUTH_USER_MODEL, models.DO_NOTHING, related_name='company')
# you can name company with something of your own choice.
# following will be more appropriate.
user = models.ForeignKey(
FutsalUser, models.DO_NOTHING, related_name='company')
[ 2 ] once you have a related_name, you can fetch the companies values as following.
FutsalUser.objects.all().values('email', 'is_active', 'company__name', 'company__hr_email')
2. Apart from that you can fetch the details from Company
table instead.
Company.objects.all().values('name', 'user__email') # you can add more field if you want.
3
users = FatalUser.objects.all()
for user in users:
company_list = user.company_details
# this company_list will have the companies associated with user.
print(company_list)
for company in company_list:
print(company.name, company.hr_email)