0

I am trying to access oneToOne relationship, but didn't work for me.

according to this documentation https://docs.djangoproject.com/en/2.0/topics/db/examples/one_to_one/

A Restaurant can access its place:

>>> r.place
<Place: Demon Dogs the place>
A Place can access its restaurant, if available:

>>> p1.restaurant
<Restaurant: Demon Dogs the restaurant>

here my model.py

class Employee(models.Model):
    idemp = models.CharField(max_length=100)
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

class EmployeeDetail(models.Model):
    nationality = models.CharField(max_length=50)
    employee = models.OneToOneField(Employee,on_delete=models.CASCADE,primary_key=True,)

here my view.py

class EmployeeListView(ListView):
    context_object_name = 'employees'
    model = models.Employee

and here my employee_list.html

{% for employee in employees %}
    <tr>
        <td>{{ employee.idemp }}</td>
        <td>{{ employee.name }}</td>
        <td>{{ employee.nationality }}</td>
    </tr>
{% endfor %}

run it and result only show idemp and name.

did I miss something?...

also

I do separate table into 2 table for employee and employe details since I have access the data and will only show 4 column for the list of employee, and other ( details ) will access all column.

which is better?...

1. use one table for many columns

or

2. split the table into 2 or more for many columns ( like my case I split employee and employeedetails )

please explain with why and because, my brain little bit slow.

Many thanks

Dicky Raambo
  • 531
  • 2
  • 14
  • 28

1 Answers1

4

You can access reverse OneToOne field with modelname attribute, employeedetail in your case. To get nationality you need to do employee.employeedetail.nationality. Try this:

{% for employee in employees %}
    <tr>
        <td>{{ employee.idemp }}</td>
        <td>{{ employee.name }}</td>
        <td>{{ employee.employeedetail.nationality }}</td>
    </tr>
{% endfor %}
neverwalkaloner
  • 46,181
  • 7
  • 92
  • 100
  • thanks its work, can you suggest me `better use separate table, or make it one table` for many columns model?... – Dicky Raambo May 05 '18 at 03:16
  • @DickyRaambo it depends. Check this question https://stackoverflow.com/questions/12318870/when-i-should-use-one-to-one-relationship – neverwalkaloner May 05 '18 at 03:26