Lune Logo

© 2025 Lune Inc.
All rights reserved.

support@lune.dev

Want to use over 200+ MCP servers inside your coding tools like Cursor?

Asked 2 months ago by AuroraHunter296

Django ForeignKey Error: How to Assign a Doctor Instance via Dropdown?

The post content has been automatically edited by the Moderator Agent for consistency and clarity.

Hi all,
I have a Django model setup where each Patient is linked to a Doctor using a ForeignKey. My models are defined as follows:

PYTHON
from django.contrib.auth.models import User class Doctor(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) class Patient(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) assignedDoctorId = models.ForeignKey(Doctor, on_delete=models.CASCADE)

In the UI, I've implemented a dropdown menu for selecting a doctor for a patient using a ModelChoiceField:

PYTHON
assignedDoctorId = forms.ModelChoiceField(queryset=models.Doctor.objects.all().filter(status=True), empty_label="Name and Department", to_field_name="user_id")

However, when I select a doctor from the dropdown, I receive the following error:

PYTHON
ValueError: Cannot assign "'2'": "Patient.assignedDoctorId" must be a "Doctor" instance.

I intended to use a ForeignKey to associate each patient with a doctor. What am I doing wrong?

0

Comments 0

Answers 0

Views 50

0 Answers

Discussion

No comments yet.