Prometheus
Prometheus

Reputation: 33625

Using Django ORM to get a related model in a method

Giving the following models...

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

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)

From project I want to get the Users Profile bio, this is how I'm doing it....

    def get_profile_bio(self):
        return Profile.objects.get(user=self.user)

I now print a list of all projects I can get a profile bio, but is this the right way to do it? I'm worried that for every project it makes a new SQL call to the DB, is this correct?

Upvotes: 0

Views: 53

Answers (1)

petkostas
petkostas

Reputation: 7450

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

Upvotes: 1

Related Questions