Modelling many to one

Hi All,
My goal here is to create fill the database with many to one relationship. What I mean by this is for example, a hospital can have multiple doctors, so all the doctors which belongs to the same hospital will have the same hospital _id/name. So, this what I am trying to achieve. I am totally new to django. What I came across as a solution is to use modelset_factory. But I am not able to apply it

model.py
from django.db import models
class HospitalDataModel(models.Model):
hospital_name = models.CharField(max_length=50)

def __str__(self):
    return f"Hospital Added: {self.hospital_name}"

class StaffDataModel(models.Model):

first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
dept_name = models.CharField(max_length=50)
doctor_id = models.IntegerField()
username = models.CharField(max_length=15, null=True)
password = models.CharField(max_length=20, null=True)
# Since a single hospital can have multiple staff that is why one to many
hospital = models.ForeignKey(HospitalDataModel, on_delete=models.CASCADE)

def __str__(self):
    return f"Doctor {self.first_name} {self.last_name}"

views.py
from django.shortcuts import render, redirect
from .forms import UserCreationForm
from django.contrib import messages
from .models import StaffDataModel, HospitalDataModel
from django.forms import modelformset_factory

    def register(request, hospital_id):
        hospital = HospitalDataModel.objects.get(pk=hospital_id)
        staff_formset = modelformset_factory(StaffDataModel, form=UserCreationForm)
        if request.method == "POST":
            formset = staff_formset(request.POST, queryset=StaffDataModel.objects.filter(hospital_id=hospital.id),
                                    )
            # form = UserCreationForm(request.POST)
            # print(form.errors)

        if formset.is_valid():
            instances = formset.save(commit=False)
            for instance in instances:
                instance.hospital_id = hospital.id
                instance.save()
            # # print(form.fields)
            # username = form.cleaned_data.get('username')
            # messages.success(request, f'User {username} Registered')
            return redirect('app-workspace')

    formset = staff_formset(queryset=StaffDataModel.objects.filter(hospital__id=hospital.id))
        # form = UserCreationForm()
    return render(request, 'users/register.html', {'form': formset})

forms.py
from django import forms
from random import randrange as rand_num
from .models import HospitalDataModel, StaffDataModel

class UserCreationForm(forms.ModelForm):

    first_name = forms.CharField(label='First Name', max_length=100)
    last_name = forms.CharField(label='Last Name', max_length=100)
    username = forms.CharField(label='Username', max_length=100)
    dept_name = forms.CharField(max_length=50, required=False)
    doctor_id = forms.IntegerField(initial=str(rand_num(0,100)))
    doctor_id.disabled = True
    hospital = forms.CharField(label='Hospital', max_length=12, required=False)
    password = forms.CharField(widget=forms.PasswordInput())
    class Meta:
        model = StaffDataModel
        fields = [ 'doctor_id', 'first_name', 'last_name', 'username', 'password']

Without digging into all the details with your code, I will encourage you to work hard to not confuse yourself between your Models and your Forms. They are two distinct “things” within Django.

Creating a Model of a many-to-one is as simple as defining a ForeignKey field on the “many” side of the relationship (Doctor having a ForeignKey to Hospital - this ignores the possibility of a Doctor having rights in multiple hospitals, which would require a many-to-many between them, but that’s a different issue.)

Once you’ve defined this relationship, then yes, you can use formsets to create forms allowing you to display and manage these relationships. Just don’t get to thinking that the formset defines the relationship - it’s just a a tool allowing you to visualize and edit it.

Thanks Ken. If “formset defines the relationship - it’s just a a tool allowing you to visualize and edit it” then what concept will help me storing the values of one-to-many relationship into database. I am working on taking values from the user and storing them into database with one-to-many relation.

I created a Foreign key of Hospital to Doctors and try to store the values I dont see the relationship. I believe during POST method I am doing something wrong or my Forms Meta class is messed up.

If you haven’t worked through either the official Django Tutorial or the Django Girls tutorial, I suggest you do so. Both work with examples dealing with modeling many-to-one relationships and show at least one way to manage those relationships (but neither demonstrates formsets). For example, the official tutorial references Poll questions and Choices, where each question has multiple Choices related to it.

I always recommend that as a starting point.

1 Like