将 child object 中的特定字段连接到 parent object 中?

Concatenate a specific field from child objects into parent object?

我有两个模型:

class Chapter(models.Model):
    chapter = models.IntegerField()
    verses_amount = models.IntegerField()
    chapter_content = models.TextField()
    

class Verse(models.Model):
    chapter = models.ForeignKey(Chapter, on_delete=CASCADE)
    verse = models.TextField()
    verse_number = models.IntegerField()

Verse,我在 verse 字段中存储了一个段落。 我如何查询所有 children (Verse),获取他们的 verse 段落,连接所有这些并将其放入 Chapter.chapter_content?

例如

verses = Verse.objects.filter()[0:2]
for verse in verses:
    print(verse.verse)

>> 'Lorem Ipsum.'
>> 'Second Lorem Ipsum Iteration 2.'

在 parent Chapter 中,我希望 chapter_content 将两个值保存为一个长字符串:

'Lorem Ipsum. Second Lorem Ipsum Iteration 2.'

你可以这样做:

chapter = Chapter.objects.get(chapter=1)  # or whatever chapter you want to get

content = ""

for verse in chapter.verse_set.all():
   content += f"{verse.verse} "

content = content.rstrip()

chapter.chapter_content = content
chapter.save()

但是将经文存储在 Verse 对象中和在 Chapter 对象中一样是不好的做法,因为如果您只想更新一节经文怎么办?

您可以尝试使 chapter_content 成为 Chapter 模型中的方法 属性。

class Chapter(models.Model):
    chapter = models.IntegerField()
    verses_amount = models.IntegerField()

    @property
    def chapter_content(self):
        content = ""
        for verse in self.verse_set.all():
            content += f"{verse.verse} "
        return content.rstrip()
    

class Verse(models.Model):
    chapter = models.ForeignKey(Chapter, on_delete=CASCADE)
    verse = models.TextField()
    verse_number = models.IntegerField()

请注意,您仍然需要按序号对经文进行排序。