获取相关字段m2m django虽然

时间:2014-10-25 15:55:46

标签: python django has-many-through m2m

嗨,我是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 %}

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

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

提前致谢

1 个答案:

答案 0 :(得分:0)

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

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