0

this problem drives me crazy. I have a Django ORM model:

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'

Template:

{% 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>

The view:

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

My API does not yield any errors, but it just won't display the person's first_nm_rus. It's blank !!!

Rahul Gupta
  • 46,769
  • 10
  • 112
  • 126
Edgar Navasardyan
  • 4,261
  • 8
  • 58
  • 121

1 Answers1

2

You don't have any relation named person_details between PersonUnique and PersonDetails, i guess you wanted to add a related_name='person_details' to your ForeignKey person_unique but it is not atm, so you should solve the issue doing:

person_unique = models.ForeignKey('person.PersonUnique', on_delete=models.CASCADE, related_name='person_details')
trinchet
  • 6,753
  • 4
  • 37
  • 60
  • Fantastic. So I have to specify related_name not only for prefetched_related, but also for select_related ? I just don't understand what this redundancy is made for ? I specify foreign key. Then why do we need related_names ? – Edgar Navasardyan Jun 04 '16 at 14:34
  • `related_name` is the name of the relation (reverse), if you want to fetch values of the related object during a query then you need to tell using `select_related`, See more here http://stackoverflow.com/questions/2642613/what-is-related-name-used-for-in-django and https://docs.djangoproject.com/en/1.9/topics/db/queries/#backwards-related-objects – trinchet Jun 04 '16 at 14:38