在Django管理中的for循环中创建另一个模型对象 [英] Create another model objects in django admin within a for loop

查看:168
本文介绍了在Django管理中的for循环中创建另一个模型对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对django完全陌生,以前是php编码器,所以如果我很笨,请忍受我. 我在应用程序中定义了三种模型:理解力,问题,答案.每个理解都有多个问题和答案,在理解模型中定义为内联".问题由管理员直接输入,但答案会根据理解自动添加. 我要实现的是,将理解理解分解为句子,并使用当前理解的外键将每个句子添加为答案对象. 我正在尝试覆盖Comprehension模型中的save方法.但是当我单击保存"时,它会出现实例错误

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.

以下是models.py的内容

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)

admin.py中的内容

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)

我也遵循了页面中提到的方法.但是,关于如何使用Comprehension模型的外键在提交条件下创建对象的空白.

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.

推荐答案

您应使用self而不是self.pk,并注意self引用当前对象.

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

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

从追溯中可以清楚地看出,Answer模型的ComprehensionAnswer属性期望使用Comprehension模型的对象.但是,您正在传递该对象的ID.

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.

这篇关于在Django管理中的for循环中创建另一个模型对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆