-1

I have two model employee and department. Employee has one to one connection with department like

class Employee(models.Model): 
      department = models.ForeignKey(to=Department, on_delete=models.CASCADE)

but when I try to create object from rest request, it throws

ValueError: Cannot assign "{'id': 1, 'name': 'wrewrwerwe'}": "Employee.department" must be a "Department" instance.

2
  • Show us the relevant views.. Commented May 14, 2021 at 10:47
  • Can you share the code fragment (likely view) where you create the Employee model object. Commented May 14, 2021 at 10:50

1 Answer 1

1

I guess you are posting a JSON, with a field department which is the primary key of the department you want to link (or a JSON representing the department).

When creating your model, you must not provide the primary key of the department for the department keywork, but provide a Department object.

In your view, you should do :

# You have data like : {"department": {"id": 1, "name": "wrewrwerwe"}, with 1 the department's PK
department = Department.objects.get(pk=data["department"]["id"])
employee = Employee(department=department)
employee.save()   # Should work
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.