How do i get the auto increment from my primary key to my foreign key the moment i create a new question

Viewed 87

I have two tables called questions and modelanswer

class Questions(models.Model):
    question_id = models.AutoField(primary_key=True)
    question = models.TextField()

    class Meta:
        db_table = "QUESTIONS"
class Answer(models.Model):
    question_id = models.ForeignKey(
        Questions, on_delete=models.CASCADE, db_column="question_id"
    )
    answer_id= models.AutoField(primary_key=True)
    model_ans = models.TextField()
    
    class Meta:
        db_table = 'MODEL'
@require_http_methods(["POST"])
@login_required
def create_question(request):
    req = json.loads(request.body)
    question = req["question"]
    answer = req["answer"]
    models.Questions.objects.get_or_create(
        question=question,
    )
    for answer in answers:
        models.Answer.objects.create(
         #question_id=(the auto increment of the new question id from question table after question is created)
         question_id=models.Questions.objects.get(pk=question_no)
         model_ans=answer["model_ans"],
        )

    return success({"res": True})

A new question id will be incremented after a new question is created, and what i would like to do is get the new question_id that was just created and pass it to the foreign key in my answers table,however i do not know how to do it, i tried using the question_id=models.Questions.objects.get(pk=question_no) to get it but it gives me a keyerror,is there another way to do it?

1 Answers

get_or_create returns the object and a boolean that indicates whether it was created. Hence you should simply use the object returned by it while making the Answer object:

question, created = models.Questions.objects.get_or_create(
    question=question,
)
for answers in answer: # the looped variable is singular and the loop variable plural? Bad variable naming...
    models.Answer.objects.create(
        question_id=question,
        model_ans=guided_answers["model_ans"], # What is guided_answers??? You may get an error here
    )

Note: Naming a foreign key as <something>_id is not great as Django automatically creates a virtual field for the foreign key as <field_name>_id which can be used to access the id instead of the related object, meaning there is a field question_id_id for your model Answer.

Related