简体   繁体   中英

Referencing Variables in Another Django Model with Foreign Key

I have a Project Model where a user can add a Project with an associated Position(s) for the Project. As an example, Website would be project whereas web developer would be the Position. Here are two models.

class Project(models.Model):
    owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='project')
    created_at = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=255)
    description = models.TextField()
    complete = models.BooleanField(default=False)

    def __str__(self):
        return self.title.title()


class Position(models.Model):
    project = models.ForeignKey(Project, default='',related_name='positions')
    name = models.CharField(max_length=140)
    description = models.TextField()
    skill = models.ForeignKey(Skill, default='')
    filled = models.BooleanField(default=False)

    def __str__(self):
        return '{} - {}'.format(self.project.title.title(), self.name.title())

I have a view created to show the user's profile and any current or past projects worked on. See below:

class ProfileView(LoginRequiredMixin,generic.TemplateView):
    template_name = 'accounts/profile.html'
    login_url = settings.LOGIN_REDIRECT_URL

    def get_context_data(self, **kwargs):
        context = super(ProfileView, self).get_context_data(**kwargs)
        lookup = kwargs.get('username')
        user = models.User.objects.get(username=lookup)
        profile = models.UserProfile.objects.prefetch_related('skills').get(user=user)
        context['profile'] = profile
        context['skills'] = [skill for skill in profile.skills.all()]

        projects = models.Project.objects.all()
        context['current_projects'] = projects.filter(Q(owner=user) & Q(complete=False))
        context['past_projects'] = projects.filter(Q(owner=user) & Q(complete=True))
        return context

I'm having trouble figuring out how to reference the position(s) for a particular projects in my html template. I know that if i try in python shell, i can query the position class and get all objects and then grab the project variables from there.

I tried to create a position 'context' in the view like this:

positions = m.Position.objects.all()
        context['positions'] = positions.filter(Q(owner=user)& Q(complete=False))

But Django doesn't like that 'owner' variable--which i understand since i'm just grabbing data from positions. I know in the shell i can do something like m=Position.objects.all() and then do a m[0].project.title to get the project data. For some reason i just can't understand how to put it all together in the code. Any help is greatly appreciated! Been racking my brain on this one for a while!

To traverse related objects, you can use the lowercased name of the model followed by __ (2 underscores) and the field name in the other model.

So instead of this:

 positions.filter(Q(owner=user)& Q(complete=False)) 

Write like this:

positions.filter(Q(project__owner=user) & Q(project__complete=False))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM