I am logged in into my application as institute user and I have to save student details. Student Model have a column as FK to Institute Model.
institute = models.ForeignKey('institute.InstituteDetailsModel', to_field="sys_id", on_delete = models.SET_NULL, null=True, blank=True)
Every-time I register student, I have to hit the DB to get institute instance and use it while saving student details. This DB-hitting situation is arising at many places when doing other things.
To avoid hitting DB everytime I tried doing below things:
Get the institute instance from DB at login time and
1. convert it to dict using model_to_dict (dates needs to be handled separately because of serialisation issue) and store in session.
2. serialize it using django's serialization framework and store in session.
But I am getting below issues in above methods respectively:
1. Using ModelForms to save data.
data["institute_id"] = request.session["institute"]["id"]
form = StudentForm(data)
got error "this field is required" for institute.
- I tried to deserialized the saved object but it is of type generator and not of type model instance hence got the errors
'generator' object has no attribute 'id
and'DeserializedObject' object has no attribute 'id'
when tried getting id attribute.
What is the best way to retrieve and store the institute mode instance only once and use it eveytime as foreign key without hitting DB?