Django Get Related with Multiple Models

101 views
Skip to first unread message

Ronaldo Bahia

unread,
Oct 19, 2014, 10:45:50 AM10/19/14
to django-d...@googlegroups.com

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

If anyone can help me with this, I'd appreciate.

Here is the question in stackoverflow: http://stackoverflow.com/questions/26451588/django-get-related-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?

Thanks.

Ronaldo

Shai Berger

unread,
Oct 19, 2014, 5:21:58 PM10/19/14
to django-d...@googlegroups.com
Hi Ronaldo,

This forum is dedicated to discussions about the development *of* Django; for
questions about development *with* Django, please use the django-users list.

Thanks,
Shai.
Reply all
Reply to author
Forward
0 new messages