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.
Asked 2 months ago by AuroraHunter296
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:
PYTHONfrom 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:
PYTHONassignedDoctorId = 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:
PYTHONValueError: 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?
Comments 0
•Answers 0
•Views 50
No comments yet.