How to put other model classes belonging (linked) to a main model class. And how to write this in Views.py. (This is Not FK)
I have a main model, called "Employees", and I need to link to it another 16 model classes (Employees Additional Data, Employees Observations, etc) in the same app. What would be the best way to write these classes in models.py?
Could be like that?
class Employees(models.Model):
class Meta:
db_table = "employees"
#fields
#fields
class EmployeesObs(models.Model):
class Meta:
db_table = "employeesobs"
#fields
#fields
class EmployeesAdditionalData(models.Model):
class Meta:
db_table = "employeesaditional"
#fields
#fields
Now, in this views.py i need:
Explaining this in the template, I need to have these other tabs (Employees Additional Data, Employees Observations, etc) in the employee register, as in the image:
Now how do I write this in views.py? I'm using Class Based Views. Can someone help me by giving me an example of code, function or documentation?
Part of code in CBV:
class AddEmployeesView(SuccessMessageMixin, CreateView):
model = Employees
form_class = EmployeesForm
template_name = '../templates/employees/form_employees.html'
success_url = reverse_lazy('list_Employees')
success_message = "Employees %(EmployeesNome)s Added!"
class EditEmployeesView(SuccessMessageMixin, UpdateView):
model = Employees
form_class = EmployeesForm
template_name = '../templates/employees/form_employees.html'
success_url = reverse_lazy('list_Employees')
success_message = "Employees %(EmployeesNome)s Edited!"
I tried to put the other model names in the "model" part of the CBV, but I got errors.
You'll need to use a foreign key to your Employee model :
class Employee(models.Model):
class Meta:
db_table = "employees"
#fields
#fields
class EmployeesObs(models.Model):
class Meta:
db_table = "employeesobs"
employee = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='observations')
#fields
class EmployeesAdditionalData(models.Model):
class Meta:
db_table = "employeesaditional"
employee = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='additional_data')
#fields
Then you can use CBV for these models as well. You can either add one observation at once or you can use an inline formset to add/edit multiple children at once. Just keep in mind that these tabs can't be accessed before the employee is first created (because you need the ID to link to it)
