Friday, November 25, 2016

Model's Foreign Key Id Attribute not being updated

I have a Question model and a Choice model where a Question can have many Choices so the Choice model has a Foreign Key mapping to a Question.

models.py:

from django.db import models


class Question(models.Model):
    text = models.CharField(max_length=200)
    title = models.CharField(max_length=200)
    total_response_count = models.IntegerField()
    topic = models.CharField(max_length=20)
    sequence_num = models.IntegerField()
    select_multiple = models.BooleanField(default=False)

    def __str__(self):
        return self.text


class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    text = models.CharField(max_length=200)
    response_count = models.IntegerField()
    response_percent = models.FloatField()

    def __str__(self):
        return self.text


I need to parse a csv file containing these models and insert them into a database. 
I want to be efficient and bulk create these models instead of having to call save() after creating each model.
I can bulk create the Questions but then when I try to bulk create the Choices I get an IntegrityError about the Choice's foreign key id attribute ("question_id") violating a not-null constraint.
After creating the Questions, the Question's id attribute gets updated but the Choice's question_id attribute does not get updated and it does not get re-evaluated when the Choice is created.

Here's a simplified version of what I want to do:
from censustest.models import Question,Choice

q=Question(text="Q1",title="",topic="",sequence_num=0,total_response_count=0)
c=Choice(text="C1",response_count=5,response_percent=0.3,question=q)
print("q.id %s, c.question %s, c.question_id %s" % (q.id, c.question, c.question_id)) # None,Q1,None
Question.objects.bulk_create([q])
print("After creating q: q.id %s, c.question %s, c.question_id %s" % (q.id, c.question, c.question_id)) # valid id,Q1,None
Choice.objects.bulk_create([c]) # ERROR: IntegrityError

Output:

Is this a bug with Django
(the foreign key id attribute not being updated) or is there a better way to do it?

An alternative approach I thought of was to assign the Choice's Question after creating the Questions and this works.
from censustest.models import Question,Choice

q=Question(text="Q1",title="",topic="",sequence_num=0,total_response_count=0)
c=Choice(text="C1",response_count=5,response_percent=0.3)
print("q.id %s" % (q.id)) # None,Q1,None
Question.objects.bulk_create([q])
c.question=q
print("c.question %s, c.question_id %s" % (c.question, c.question_id)) # Q1,valid id
Choice.objects.bulk_create([c]) # works, no error

Output:

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/ddbf736b-2034-4d27-ae19-c4180b0a1bdf%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment