0

我有 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()

所以,我有许多礼堂和professionals_name_id。但我需要完整的教授姓名,而不是身份证。怎么做?

4

2 回答 2

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单独检索名称。

于 2012-10-19T17:11:23.107 回答
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')
于 2012-10-19T17:49:52.587 回答