fetching linked table values

I am trying to get the values from Centre model via SubCentre model.
Using the subcentre ‘pk’ I am trying to fetch the Centre model data to auto-populate a form.

models.py

class Centre(models.Model): 
    Ccode = models.AutoField(primary_key=True)
    Cname = = models.CharField(max_length=50, blank=True, null=True)
    .....
    def __str__(self):
        return str(self.Ccode)

class SubCentre(models.Model):
    Ccode = models.ForeignKey(Centre, blank=True, null=True, on_delete=models.SET_NULL, to_field="Ccode", related_name="Ccode")
    Cname = models.CharField(max_length=50, blank=True, null=True) # holds Cname value of Centre
    name = models.CharField(max_length=50, blank=True, null=True)
    ...............
   
    def __str__(self):
        return str(self.name)

class StudEntry(models.Model):
    
    Ccode = models.ForeignKey(Centre, blank=True, null=True, on_delete=models.SET_NULL, to_field="Ccode", related_name="Ccode")
     ...........

forms.py

class StudentEntryForm(forms.ModelForm):
    class Meta:
        model = StudEntry
        fields = "__all__"

views.py

def StudentEntry(request,pk):
    subcentre = SubCentre.objects.get(pk=pk)  
    centre = Centre.objects.get(Ccode=subcentre.Ccode)  # <= error is shown in this line
    form = StudentEntryForm(request.POST or None, instance=subcentre)

    if request.method == "POST":
        if form.is_valid():
            book = form.save(commit=False)
            book.CCode = subcentre.Ccode
            # book.zone = centre.zone
            book.Cname = subcentre.Cname
            book.save()
            return redirect('subcentre-list')
        else:
            return render(request,"Students/CreateEntry.html",{'form':form, 
        'subcentre':subcentre, 'centre':centre})


    context = {
        'form':form, 
        'subcentre':subcentre, 
        'centre':centre
        }
    return render(request,"Students/CreateEntry.html",context)

urls.py

urlpatterns = [ 
    path('<pk>/',StudentEntry,name='book-entry')
]

But getting the error as below,
Unable to fix the issue. Request help on the same. - Thank you!

Django Version: 4.1
Exception Type: TypeError
Exception Value: Field ‘Ccode’ expected a number but got <Centre: 634>.
Exception Location: F:\Program Files\Python310\lib\site-packages\django\db\models\fields_init_.py, line 2020, in get_prep_value
  • The above exception (int() argument must be a string, a bytes-like object or a real number, not ‘Centre’) was the direct cause of the following exception:

  • F:\Program Files\Python310\lib\site-packages\django\core\handlers\exception.py, line 55, in inner

in the following line of the above view,

centre = Centre.objects.get(Ccode=subcentre.Ccode)

This is actually an unnecessary query.

The expression subcentre.Ccode is, in the ORM, a reference to the Centre object.

So, centre = subcentre.Ccode accomplishes what you’re looking for here.

1 Like

My unfortune.

There are many other fields in that Centre model, which we would like to autofill the entry form. But here those fields aren’t provided in the code.
So was trying to fetch the whole record set of that Centre model via CCode captured from subcentre.
The CCode value is needed in the form ‘book’ and already subcentre.Ccode is being used, still that too is not working.

Could you please guide where I am going wrong? - Thank you!

I’m sorry, I’m not understanding what you’re asking for here. What do you mean by “record set”? Your SubCentre model has an FK to Centre, which means that given an instance of SubCentre, there’s only one instance of Centre related to it.

Please post the code that is not working, along with the details of what you’re trying to do.

centre = Centre.objects.get(Ccode=subcentre.Ccode)

The error is with the above line.

Yes, record set, I meant all the field values of that 1 Centre.

I would like to make the following work (whole view code is in the question).
Like book.zone = centre.zone, there are other field values which I am trying to populate in the form.

if form.is_valid():
            book = form.save(commit=False)
            book.CCode = subcentre.Ccode
            book.zone = centre.zone
            book.Cname = subcentre.Cname
            book.save()
            return redirect('subcentre-list')
        else:

Issue is, 1. even the Subcentre.Ccode nor subcentre.Cname dosen’t get populate
2. error is thrown with variable ‘centre’ which is to hold all fields values of the linked centre.

I am unable to find source of the issue.

Correct - because the error is in the redundant and unnecessary query.

centre = subcentre.Ccode sets centre to an instance of Centre if subcentre is an instance of SubCentre.

What I see from what you have posted:

Your form is a ModelForm built from StudEntry.

You show StudEntry as:

In your view you have:

I see no field in StudEntry named CCode. (I see a field named Ccode, but that’s not the same thing.)

You also don’t show a field named Cname in StudEntry either.

1 Like

Thank you Ken!! Right its a typo. Did correct it, still the code didn’t work.

The following worked now, when it wasn’t working before in another app.

initial_dict = {‘Ccode’:subcentre.Ccode, ‘zone’:centre.zone, ‘centre’:subcentre.Cname}
form = StudentEntryForm(request.POST or None, initial=initial_dict, instance=subcentre)

Thank you so much Ken sir!!