Search code examples
django-ninja

How to create record with ForeignKey (ValueError)


(Im using django-ninja-extra)

So i have read the crud example of Django Ninja and a Video of Bugbytes (Django-Ninja APIs - Modern API Development in Django), but when i try to remake it, then i get following error.

ValueError: Cannot assign "1": "employee.department_id" must be a "department" instance.

But in BugBytes Video it just works fine. How can i make a Post request, which sends the Foreignkey as a integer?

I have following code :

api.py:

from ninja_extra import api_controller, route, NinjaExtraAPI, permissions
from django.shortcuts import get_object_or_404
from ninja import Schema, constants
from datetime import datetime
from .models import department, employee
from typing import List
from ninja_jwt.controller import NinjaJWTDefaultController
from ninja_jwt.authentication import JWTAuth

api = NinjaExtraAPI()

class DepartmentIn(Schema):
    name: str
    last_modified: datetime

class DepartmentOut(Schema):
    id: int
    name: str
    last_modified: datetime

class EmployeeIn(Schema):
    name: str
    last_modified: datetime
    department_id: int

class EmployeeOut(Schema):
    id: int
    name: str
    last_modified: datetime

@api_controller('', permissions=[])
class ForeignkeyhandlingController:
  
    @route.post("department/create", auth=constants.NOT_SET)
    def create_department(self, payload: DepartmentIn):
        department.objects.create(**payload.dict())

    @route.post("employee/create", auth=constants.NOT_SET)
    def create_employee(self, payload: EmployeeIn):
        employee.objects.create(**payload.dict())

api.register_controllers(NinjaJWTDefaultController, ForeignkeyhandlingController)

models.py:

# Create your models here.
from django.db import models
from django.conf import settings


class department(models.Model):
    name = models.CharField(max_length=50)
    last_modified = models.DateTimeField(auto_now=True, auto_now_add=False)
class employee(models.Model):
    name = models.CharField(max_length=50)
    last_modified = models.DateTimeField(auto_now=True, auto_now_add=False)
    department_id = models.ForeignKey(department, on_delete=models.CASCADE)

Following is my Request:

curl -X 'POST' \
  'http://127.0.0.1:8000/api/employee/create' \
  -H 'accept: */*' \
  -H 'Content-Type: application/json' \
  -d '{
  "name": "string",
  "last_modified": "2024-12-12T16:44:33.897Z",
  "department_id": 1
}'

Solution

  • so the Problem is pretty simple:

    I didnt know that the Foreignkeys name is being generated, so i just defined them with a _id, but django does that job already, so i had a department_id_id and tried to access that with department_id :)