0

I am a new user to Django, I have two models, one is Department and the other is Employee. I need to link these two tables so that I would be able to view the details under each department in a table. But I am getting an error as "NOT NULL constraint failed: pom_employee.department_id". I am not using forms in this project. Kindly help me

In models.py

class Department(models.Model):
    name = models.CharField(max_length=50)

    def __str__(self):
        return self.name

class Employee(models.Model):
    name = models.CharField(max_length=124)
    age = models.IntegerField()
    department = models.ForeignKey(Department,on_delete=models.CASCADE,null=True)

    def __str__(self):
        return self.name

In views.py

def empdata(request):
    if request.method == "POST":
        name = request.POST.get('empname', False)
        age = request.POST.get('empage', False)

        try:
            Employee.objects.create(name=name, age=age)

            return redirect('/showemp')
        except Employee.DoesNotExist:
            print("I am in except")
            Employee.objects.get(name=name, age=age).save()
    return render(request, 'showempdetails.html')
g3tl0st
  • 763
  • 1
  • 6
  • 20
  • I think if you add not null in the name field in 'Department' it works (if it works tell me to explain this) – Alireza Jul 29 '21 at 08:06
  • 1
    If you added `not null` after your first migration, make sure you have migrated after your edit to work as expected. Migration: `python manage.py makemigrations` And Migrate: `python manage.py migrate` – Biplove Lamichhane Jul 29 '21 at 08:16
  • I think you have some un-applied migrations. Please run your migrations and check if that helps. – Ram Jul 29 '21 at 08:19
  • @Ram I did python manage.py makemigrations and python manage.py migrate – Devika B Raj Jul 29 '21 at 10:40
  • @Alireza I am not able to add not null in name field as it shows red underline. I have added as null=False, is it correct? – Devika B Raj Jul 29 '21 at 10:44
  • 1
    You can go through this post: https://stackoverflow.com/questions/25964312/not-null-constraint-failed-after-adding-to-models-py – Ram Jul 29 '21 at 10:49

2 Answers2

0

You can try this one. If it gives any error then let me know what it says:

class Department(models.Model):
    name = models.CharField(max_length=50)

    def __str__(self):
        return self.name

class Employee(models.Model):
    name = models.CharField(max_length=124)
    age = models.IntegerField()
    department = models.ForeignKey(Department,on_delete=models.CASCADE,null=True, blank=True)

    def __str__(self):
        return self.name


views.py

    def empdata(request):
        if request.method == "POST":
            name = request.POST.get('empname')
            age = request.POST.get('empage')
            
            try:
                emp = Employee(name=name, age=age)
                emp.save()
                return redirect('/showemp')
            except Employee.DoesNotExist:
                print("I am in except")
        return render(request,'showempdetails.html')

You can delete your old migrations and run again new migrations.

Jafoor
  • 695
  • 5
  • 14
  • Thankyou for your reply but I am getting the same error as before. @Jafoor – Devika B Raj Jul 29 '21 at 10:39
  • @DevikaBRaj I can't see anything wrong in code, you just can delete your `migrations` and `db.sqlite3` files and remigrate. – Jafoor Jul 29 '21 at 12:12
  • As you said I deleted db.sqlite3, did makemigrations and migrate and happy to say that error has been removed and the data is getting added to the table . Now the problem is foreignkey field(department_id) is not showing any value, displaying as NULL. – Devika B Raj Jul 30 '21 at 10:02
  • @DevikaBRaj you are not adding any value of` foreignkey` in `views.py` file. So it's showing `null`. – Jafoor Jul 30 '21 at 10:06
0

if you want blank then don't use cascade

    department = models.ForeignKey(Department,on_delete=models.CASCADE,null=True, blank=True)

change

    department = models.ForeignKey(Department,null=True, blank=True)
mstgnz
  • 2,988
  • 1
  • 9
  • 13
  • If I delete the department name , it should warn the user regarding the data link with department that is why I used CASCADE, so should I go with it or not? @Mesut GENEZ – Devika B Raj Jul 29 '21 at 10:43