Django - 访问select_related字段

时间:2016-06-04 14:07:07

标签: django

这个问题让我抓狂。 我有一个Django ORM模型:

class EmployeeUnique(models.Model):
    person_unique = models.OneToOneField(PersonUnique,  on_delete=models.CASCADE, primary_key=True, related_name = 'employee_unique')
    class Meta:
        managed = False
        db_table = 'employee_unique'

class PersonUnique(models.Model):
    birthdate = models.DateField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'person_unique'  

class PersonDetails(models.Model):
    person_unique = models.ForeignKey('person.PersonUnique', on_delete=models.CASCADE)

    first_nm_rus = models.CharField(max_length=200)

    class Meta:
        managed = False
        db_table = 'person_details'

模板:

{% for e in employee_unique_table %}
    <tr class='clickable-row' style = 'cursor:pointer' data-href="/employee_profile_main/{{e.person_unique_id}}/">
        <td>
            {% for p in e.person_unique.person_details.all %}
                <div>{{p.first_nm_rus}}</div>
            {% endfor %}
        </td>

观点:

def my_view(request):
    employee_unique_table = EmployeeUnique.objects.\
                prefetch_related('employee_legal_entity__employee_category',
                                         'person_unique').select_related()  

我的API不会产生任何错误,但它只是不会显示该人的first_nm_rus。它空白!!!

1 个答案:

答案 0 :(得分:2)

person_detailsPersonUnique之间没有任何名为PersonDetails的关系,我想你想在你的ForeignKey related_name='person_details'中加person_unique但是它不是atm,所以你应该解决这个问题:

person_unique = models.ForeignKey('person.PersonUnique', on_delete=models.CASCADE, related_name='person_details')