gpt4 book ai didi

python - 如何通过用户在 django 模板中显示与反向引用的关系?

转载 作者:行者123 更新时间:2023-11-28 22:10:22 25 4
gpt4 key购买 nike

我有这样的模型

class Employee(models.Model):
"""Employee information."""
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='employee', unique=True)
position = models.CharField("current position in a company", max_length=64, blank=True)
birth_date = models.DateField("date of birth", null=True)
skills = models.ManyToManyField(
Technology, through="Skill", verbose_name="skills", blank=True)


class Technology(models.Model):
"""Technologies."""
name = models.CharField('technology name', max_length=32, unique=True)

class Skill(models.Model):
"""Information about an employee's skills."""
LEVELS = (
('basic', 'Basic'),
('intermediate', 'Intermediate'),
('advanced', 'Advanced'),
('expert', 'Expert'),
)
employee = models.ForeignKey(
Employee, on_delete=models.CASCADE, related_name="employee_skills")
technology = models.ForeignKey(Technology, on_delete=models.CASCADE)
start_date = models.DateField(
verbose_name='Works with since:')
level = models.CharField("level", max_length=64, choices=LEVELS)

我不明白为什么我的模板代码不起作用

template.html

{{ user.employee.position }}
{{ user.employee.birth_date }}
{{ user.employee.summary }}

{% for i in user.employee.skills.all %}
{{ i.technology.name }}
{{ i.level }}
{% endfor %}

我什么都看不到。所有模型都可以在管理面板上看到。然后我使用 TemplateView,例如

class AccountView(TemplateView):

template_name = "profile.html"

def get_context_data(self, **kwargs):
context = super(AccountView, self).get_context_data(**kwargs)
context['skills'] =
Skill.objects.filter(employee__user=self.request.user)

return context

然后一切正常。

最佳答案

建模有问题。你应该使用 OneToOneFieldEmployee 之间和 User .本质上是一个 OneToOneField独一无二的 ForeignKey .然而,它会改变一些逻辑,例如 user.employee将访问相关的Employee对象,不是 QuerySetEmployee小号:

class Employee(models.Model):
# ...
user = models.<b>OneToOneField</b>(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name='employee'
)
# ...

在你的AccountView ,你统一'skills'凭借该员工的技能,确实:

class AccountView(TemplateView):

template_name = "profile.html"

def get_context_data(self, **kwargs):
context = super(AccountView, self).get_context_data(**kwargs)
context.update(
skills=Skill.objects.filter(employee__user=self.request.user)<b>.select_related('technology')</b>
)
return context

您可能想使用 .select_related(..)这里是为了防止所谓的“N+1 问题”,其中对于每个技能,您将进行额外的查询。

因此您可以通过以下方式呈现技能:

{% for skill in <b>skills</b> %}
{{ skill.technology.name }}
{{ skill.level }}
{% endfor %}

或者您可以通过以下方式访问:

{% for skill in <b>request.user.employee.employee_skills.all</b> %}
{{ skill.technology.name }}
{{ skill.level }}
{% endfor %}

虽然上面的方法不太安全,因为有可能 User没有相关Employee对象。

关于python - 如何通过用户在 django 模板中显示与反向引用的关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56848491/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com