0

Hi I'm new in Django and don't know how to get related objects with multiple models.

My code:

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

class CandidatePhotos(models.Model):
    user = models.ForeignKey(User)
    photo = models.ImageField(upload_to='usergallery/%Y/%m/%d')

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)

In the views I have

#views.py
class CandidateDetails(generic.DetailView):
    model = Candidate
    template_name = 'dashboard/candidate.html'

    def get_context_data(self, **kwargs):
        context = super(CandidateDetails, self).get_context_data(**kwargs)
        context['cand_photos'] = CandidatePhotos.objects.all()
        return context

In the template I have

<h2>{{ candidate.user.first_name }} {{ candidate.user.last_name }}</h2>

{% for candidatephotos in cand_photos %}
    <img alt="" src="{{ candidatephotos.photo.url }}" >
{% endfor %}

Here is my url dashboard/candidate/pk/.

What happens is in the template all users photos are loaded instead of only the specific user I want. I have tried to get the user photos using {{ candidate.user.candidatephotos_set.photo.url }} but it doesn't work.

I have also tried to change in views.py the model from "Candidate" to "CandidateToJob" (the through model) but I get a 404 error, I don't know why.

So, what is the best practice to achieve this?

Ronaldo Bahia
  • 576
  • 3
  • 24

1 Answers1

1

There's no need to query CandidatePhotos in the view at all. Your candidate object already had the relevant relationship, through User, so you can simply follow that:

{% for photo in object.user.candidatephotos_set.all %}
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • Hi Daniel, thanks but this is not working. Maybe because I forgot to mention that I'm logged as a "Company User". So The user I'm logged in has no photos. In this app I have two types of users: company users and candidate users. – Ronaldo Bahia Oct 19 '14 at 15:21
  • Oh sorry, I got it working using: {% for candidatephotos in object.user.candidatephotos_set.all %} Kudos. – Ronaldo Bahia Oct 19 '14 at 15:27