[Answer]-Using Django ORM to get a related model in a method

1👍

class ProjectComment(RewardBase):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, related_name="projects")

class User (AbstractBaseUser):
    email = models.EmailField()   

class Profile(models.Model):
    bio = models.CharField(max_length=80)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, unique=True, related_name="profile")

Then you can fetch the users and the profiles:

projects = ProjectComment.select_related('user', 'user__profile').exclude(user__isnull=True).all()

for project in projects:
    users = [user for user in project.user.all()]

And then:

for user in users:
    profiles = [profile for profile in user.profile.all()]

Why do you have a unique constrain in your ForeignKey? if you need Uniquness create a OneToOneField

Leave a comment