Leon
Leon

Reputation: 6544

subquery in django

I have 2 models:

class Professors(models.Model):
    professors_name = models.CharField('professor', max_length=32, unique=True)
class Discipline(models.Model):
    auditorium = models.IntegerField('auditorium')
    professors_name = models.ForeignKey(Professors)

In views:

disciplines = Discipline.objects.all()

So, I have number of auditorium and professors_name_id. But I need full profrssors name, not id. How to do it?

Upvotes: 0

Views: 502

Answers (2)

dokkaebi
dokkaebi

Reputation: 9190

Models:

# models usually named in the singular
class Professor(models.Model):
    professors_name = models.CharField('professor', max_length=32, unique=True) 
class Discipline(models.Model):
    auditorium = models.IntegerField('auditorium')
    # your pointer is to a professor, not to the name
    professor = models.ForeignKey(Professor)

In view:

# select_related('professor') to avoid a second query when accessing professor
disciplines = Discipline.objects.select_related('professor')

Template:

{% for disc in disciplines %}
{{ disc.auditorium }}: {{ disc.professor.name }}
{% endfor %}

For values:

Discipline.objects.values('auditorium', 'professor__name')

Upvotes: 1

Siva Arunachalam
Siva Arunachalam

Reputation: 7740

Django ORM will always returns the objects not the ids. You should have a design like this.

class Professor(models.Model):
    name = models.CharField('professor', max_length=32, unique=True)
class Discipline(models.Model):
    auditorium = models.IntegerField('auditorium')
    professor = models.ForeignKey(Professors)

and use discipline.professor.name to retrieve the name alone.

Upvotes: 1

Related Questions