'How columns are connected in posgresql and data autopopulate in between tables?
I have to tables that I created through models.py in Django models and connect it to postgresql db. I have a common columns in two table Departments(DepartmentName) and Employees (Department) and say we want to add new row to Employees table.
The thing that confuses me since those two columns are DepartmentName and Department are same how can we make sure when the new recors are generated in Employees table how the records are auto populated in Departments table?
"models.py"
from django.db import models
# Create your models here.
class Departments(models.Model):
DepartmentId = models.AutoField(primary_key = True) # Autoincremented department id
DepartmentName = models.CharField(max_length = 500)
class Employees(models.Model):
EmployeeId = models.AutoField(primary_key = True) # Autoincremented department id
EmployeeName = models.CharField(max_length = 500)
Department = models.CharField(max_length = 500)
DateofJoining = models.DateField()
PhotoFileName = models.CharField(max_length = 500)
After inserting new records to Employees Table in postgresql table
insert into public"Employees" values (1, 'Bob', 'IT', '2021-12-12', 'anonyms.png')
Departments Table in when we inserted new records to
So my questions are
How can we connect those two tables when new records created in one of them the other gets populated with the data ? In this case DepartmentName data in Departments table.
Solution 1:[1]
- Your models are not django neither python like models, so I'd rewrite them. Name of a model must be singular, dont use camelCase, dont duplicate name of model in name of fields.
- To solve your problem, I'd redefine
save()method inEmployeemodel.
class Department(models.Model):
name = models.CharField(max_length=500)
class Employee(models.Model):
name = models.CharField(max_length=500)
department = models.CharField(max_length=500)
date_of_joined = models.DateField()
photo_file_name = models.CharField(max_length=500)
def save(self, **kwargs):
Department.objects.get_or_create(name=self.department)
super().save(**kwargs)
By the way, use ForeignKey in Employee model for department field.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nikita |


