编写 django 查询并一次点击数据库即可获取反向相关对象!
我已经在 models.py 中编写了这些模型:
class User(models.Model): first_name = models.CharField(max_length=80) class Skill(models.Model): user = models.ForeignKey(User) title = models.CharField(max_length=80) level = models.IntegerField(default=3) class Work(models.Model): user = models.Foriegnkey(User) work_name = models.CharField(max_length=80) salary = models.IntegerField()
现在我想从数据库中获取那些用户具有一定技能的作品,并用它们渲染 html。我在views.py中编写了这段代码:
def show_works(request, skill): works = Work.objects.select_related().filter(user__skill__title=skill) return render_to_response("works.html", {'works':works})
但是我想在该html中显示另一件事:我想显示该工作的用户的名字和他的技能。我使用了 select_lated(),但我只能显示first_name,但无法达到用户的技能。
我想编写一个最佳查询来获取作品和其他额外信息,例如用户及其用户的技能!就像下面的代码: (我不想为每件作品都访问数据库来获取其用户的技能)
模板works.html:
{% for work in works %} {{work.work_name}} user is : {{work.user.first_name}} which has these skills: {% for skill in work.user.skill %} {{skill.title}} {% endfor %} {% endfor %}
i have written these models in models.py:
class User(models.Model): first_name = models.CharField(max_length=80) class Skill(models.Model): user = models.ForeignKey(User) title = models.CharField(max_length=80) level = models.IntegerField(default=3) class Work(models.Model): user = models.Foriegnkey(User) work_name = models.CharField(max_length=80) salary = models.IntegerField()
now i want to get those Works from database which their users have a certain skill, and render a html with them. i write this code in views.py:
def show_works(request, skill): works = Work.objects.select_related().filter(user__skill__title=skill) return render_to_response("works.html", {'works':works})
but there is another thing i want to show in that html: i want to show first_name of the user of that work and his skills. i used select_related(), but i can only show first_name but i can't reach user's skills.
i want to write an optimal query to get the works and the other extra informations, like user and the skills of it user! like the code blow:
( i don't want to hit database for every work to get its user's skills )
template works.html:
{% for work in works %} {{work.work_name}} user is : {{work.user.first_name}} which has these skills: {% for skill in work.user.skill %} {{skill.title}} {% endfor %} {% endfor %}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能永远不会再看这个问题,但无论如何我都会尝试回答它。
我认为这应该有效:
You'll probably never look at this again, but I'll try to answer it anyway.
I would think that this should work: