Edgar Navasardyan
Edgar Navasardyan

Reputation: 4501

Django - getting access to select_related field

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 !!!

Upvotes: 0

Views: 400

Answers (1)

trinchet
trinchet

Reputation: 6933

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')

Upvotes: 2

Related Questions