在Django中调用添加集中的字段

时间:2015-08-28 23:09:43

标签: python django

我正在尝试将名为BlockContent的模型中的字段添加到Block

    block_list = Block.objects.filter(lesson=int(num))

    # For each block, fill the stuff inside of the latest revision:
    for block in block_list:
        additional = BlockContent.objects.filter(block=block.id).latest('id')
        block.blockcontent_set.add(additional)
        print("check: ", block.content)

这一直在抛出

'Block' object has no attribute 'content'

我猜它与我如何称呼模型有关,但我似乎无法理解它。我尝试了几种不同的组合(例如block.blockcontent_set.contentblock.blockcontent.content)而没有任何运气。

目的:尝试将此变为易于使用的变量,以传递到模板中的for循环。

class Block(models.Model):
    lesson = models.ForeignKey('Lesson')
    name = models.CharField(max_length=100)

class BlockContent(models.Model):
    block = models.ForeignKey('Block')
    content = models.TextField()
    type = models.IntegerField(default=1)
    revision = models.IntegerField(default=0)
    latest = models.BooleanField(default=True)

2 个答案:

答案 0 :(得分:1)

在当前模型中,Block模型类和BlockContent模型类之间存在多对一关系,更改代码以解决错误:

block_list = Block.objects.filter(lesson=int(num))

# For each block, fill the stuff inside of the latest revision:
for block in block_list:
    additional = BlockContent.objects.filter(block=block.id).latest('id')
    block.blockcontent_set.add(additional)
    # The block.blockcontent_set contains multiple BlockContent objects
    for block_content in block.blockcontent_set.all():
        print("check: ", block_content.content)

此外,如果您希望在BlockBlockContent之间建立一对一关系,请将block班级中BlockContent属性的类型更改为OneToOneField

class BlockContent(models.Model):
    block = models.OneToOneField('Block')
    content = models.TextField()
    type = models.IntegerField(default=1)
    revision = models.IntegerField(default=0)
    latest = models.BooleanField(default=True)

然后,您必须使用blockcontent代替blockcontent_set来使用block个对象。

如果您希望在content类中简要使用BlockContent类的Block属性,可以向Block类添加属性,类似如下:

class Block(models.Model):
    lesson = models.ForeignKey('Lesson')
    name = models.CharField(max_length=100)

    @property
    def contents(self):
        return [bc.content for bc in self.blockcontents_set.all()]

然后你可以使用:

{% for content in block.contents %}
    <span>{{ content }}</span>
{% endfor %}

而不是:

{% for bc in block.blockcontent_set.all %}
    <span>{{ bc.content }}</span>
{% endfor %}

答案 1 :(得分:0)

您可以在related_field模型中使用BlockContent,同时将Block声明为ForeignKey

block = models.ForeignKey('Block', related_name='related_content')

然后,您可以使用此相关名称从BlockContent对象访问Block的记录。

所以,你的代码将是:

block_list = Block.objects.filter(lesson=int(num))

for block in block_list:
    block.related_content.all()  # related_content is the related_name