【问题标题】:Get related field m2m django though获取相关字段 m2m django 虽然
【发布时间】:2014-12-21 06:13:50
【问题描述】:

您好,我是 Django 新手,我没有在直通模型中获取相关对象。

我的代码:

#models.py
class Candidate(models.Model):
    user = models.OneToOneField(User, primary_key=True)
    birth = models.CharField(max_length=50)
    ...

class Job(models.Model):
    candidate = models.ManyToManyField('Candidate', through='CandidateToJob')
    title = models.CharField(max_length=500)
    ...

class CandidateToJob(models.Model):
    job = models.ForeignKey(Job, related_name='applied_to')
    candidate = models.ForeignKey(Candidate, related_name='from_user')
    STATUS_CHOICES = (
       ('1', 'Not approved'),
       ('2', 'Approved'),
       ('3', 'Hired')
    )
    status = models.CharField(max_length=2, choices=STATUS_CHOICES)

在我的观点中

#views.py
class Screening(generic.DetailView):
    model = Job
    template_name = 'dashboard/screening.html'

    def get_context_data(self, **kwargs):
         context = super(Screening, self).get_context_data(**kwargs)
         context['candidate_list'] = self.object.candidate.select_related().annotate
         return context

我有的模板:

 #url.py
 url(r'^dashboard/job/(?P<pk>\d+)/screening/$', views.Screening.as_view(), name='screening'),

 #HTML
 {% for candidate in candidate_list %}

     {{ candidate.user.get_full_name }} #this works 

     {% for candidatetojob in job.candidatetojob_set.all %}
          {{ candidatetojob.get_status_display }} 
     {% endfor %}

 {% endfor %}

问题是我无法获得与特定工作的候选人相关的状态。 我怎样才能得到它?

在不重新加载整个页面的情况下更新此状态的最佳方法是什么?

提前致谢

【问题讨论】:

  • 如果您想访问模板中的模型实例 - DetailView 提供的默认名称是object。所以改为job.candidatetojob_set.all试试object.candidatetojob_set.all
  • 在不重新加载整个页面的情况下更新状态的最佳方法 - 使用 AJAX(将更新的数据和对象 pk 发送到某个视图并保存在那里)
  • 谢谢。您能否提供一些如何完成 ajax 更新的示例?
  • docs.djangoproject.com/en/1.7/topics/class-based-views/… 但在你的情况下继承 UpdateView 而不是 CreateView
  • 再次感谢。我试过 object.candidatetojob_set.all 但没用。

标签: python django has-many-through m2m


【解决方案1】:

哦,我可以使用以下方法检索候选人状态:

 {% for candidate in object.applied_to.all %}
     {{ candidate.get_status_display }}
 {% endfor %}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-21
    • 2016-09-28
    • 2013-02-05
    • 2011-07-30
    • 1970-01-01
    • 1970-01-01
    • 2015-12-23
    • 2015-09-29
    相关资源
    最近更新 更多