pythondjangoinstancemodeladmin

Create another model objects in django admin within a for loop


I am completely new to django and was a php coder previously, so please bear with me if i am being dumb. I have three models defined in my app, Comprehension, Question, Answer. Each comprehension has multiple questions and answers defined as 'inline' in the Comprehension model. Questions are input directly by the admin, but answers would added automatically from the comprehension. What I want to achieve is, to split the comprehension in to sentences and add each sentence as an answer object with foreignkey of the current comprehension. I am trying to override the save method in Comprehension model. But when I click save, it gives an instance error

Cannot assign "23L": "Answer.ComprehensionAnswer" must be a "Comprehension" instance.

How do I assign/create and instance here ? or am I following a wrong approach. If so, kindly guide me to the right approach.

Following are the contents of models.py

class Question(models.Model):
    QuestionText = models.CharField(max_length=500, verbose_name='Question Text')
    QuestionTypeID = models.ManyToManyField(QuestionType, verbose_name='Question Type')
    ComprehensionQuestion = models.ForeignKey(Comprehension, verbose_name='comprehension')
    QuestionRemarks = models.CharField(max_length=500, verbose_name='remarks', null=True, blank=True)
    LastUpdate = models.DateTimeField(auto_now=True)
    def __unicode__(self):
       return self.QuestionText
    def was_published_recently(self):
       return self.LastUpdate >= timezone.now() - datetime.timedelta(1)

class Answer(models.Model):
    AnswerText = models.CharField(max_length=500, verbose_name='Answer Text')
    AnswerTypeID = models.ManyToManyField(AnswerType, verbose_name='Answer Type')
    ComprehensionAnswer = models.ForeignKey(Comprehension, verbose_name='Comprehension', null=True, blank=True)
    AnswerRemarks = models.CharField(max_length=500, verbose_name='Remarks')
    LastUpdate = models.DateTimeField(auto_now=True)
    def __unicode__(self):
       return self.AnswerText

class Comprehension(models.Model):
    ComprehensionTitle = models.CharField(max_length=100, verbose_name='Comprehension Title')
    ComprehensionsText = models.TextField(verbose_name='Text')
    ComprehensionsRemarks = models.CharField(max_length=400, verbose_name='Remarks for this Comprehension', null=True,  blank=True)
    LastUpdate = models.DateTimeField("Last Updated", auto_now=True)
    def __unicode__(self):
       return self.ComprehensionTitle
    def was_published_recently(self):
       return self.LastUpdate >= timezone.now() - datetime.timedelta(1)

    def save(self, *args, **kwargs):
       #overrides the default save function to split the comprehension paragraph into sentences and adds them as probable answers
       AnswerList = self.ComprehensionsText.split("u'\u0964'")

    for sentence in AnswerList:
        p = Answer.objects.create(AnswerText = sentence, ComprehensionAnswer = self.pk)

    super(Comprehension, self).save(*args, **kwargs)

Content inside admin.py

class ComprehensionAdmin(admin.ModelAdmin):
    form = ComprehensionForm
    fieldsets = [
    ('Main', {'fields': ['ComprehensionTitle','ComprehensionsText']}),
    ('Additional Info', {'fields': ['ComprehensionsRemarks'], 'classes': ['collapse']}),
    ]
    inlines = [QuestionInline, AnswerInline]
    list_display = ('ComprehensionTitle', 'LastUpdate')
    list_per_page = 10


class QuestionInline(admin.TabularInline): 
    model = Question
    extra = 2

class AnswerInline(admin.TabularInline):   
    model = Answer
    extra = 2

admin.site.register(Question)
admin.site.register(Answer)
admin.site.register(Comprehension, ComprehensionAdmin)

I have also followed the approach mentioned on this page. But, blank about how to create the objects in commit condition using the foreignkey of Comprehension model.


Solution

  • You should use self instead of self.pk and note that self refers the current object.

    p = Answer.objects.create(AnswerText = sentence, ComprehensionAnswer = self)
    

    From the traceback, it clearly shows that, ComprehensionAnswer attribute of Answer model expects Comprehension model's object. But you're passing the id of that object.