简体   繁体   English

使用外键在另一个Django模型中引用变量

[英]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. 我在弄清楚如何引用html模板中特定项目的位置时遇到了麻烦。 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. 我知道,如果我尝试使用python shell,我可以查询position类并获取所有对象,然后从那里获取项目变量。

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. 但是Django不喜欢该“所有者”变量-我理解这是因为我只是从位置中获取数据。 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. 我知道在shell中我可以执行m=Position.objects.all() ,然后执行m[0].project.title来获取项目数据。 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. 要遍历相关对象,可以使用模型的小写名称,后跟__ (2个下划线)和另一个模型中的字段名称。

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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