我有2个型号:
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)
观点:
disciplines = Discipline.objects.all()
所以,我有很多礼堂和教授名_id。但我需要完整的profrssors名称,而不是id。怎么做?
答案 0 :(得分:1)
Django ORM将始终返回对象而不是id。你应该有这样的设计。
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)
并使用discipline.professor.name
单独检索名称。
答案 1 :(得分:1)
型号:
# 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)
在视图中:
# select_related('professor') to avoid a second query when accessing professor
disciplines = Discipline.objects.select_related('professor')
模板:
{% for disc in disciplines %}
{{ disc.auditorium }}: {{ disc.professor.name }}
{% endfor %}
对于值:
Discipline.objects.values('auditorium', 'professor__name')