gpt4 book ai didi

Django REST Framework - 获取相关对象

转载 作者:行者123 更新时间:2023-12-04 02:02:24 25 4
gpt4 key购买 nike

我有这些模型,其中一本书可以包含不同语言的许多内容:

class Book(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
title = models.CharField(max_length=255)

class BookContent(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
book = models.ForeignKey(Book, on_delete=models.CASCADE)
content = models.TextField()
language = models.TextField()

--------------------更新--------------------

我应该如何获取 Book 及其相关 BookContent 以使结果 JSON 如下所示?
{
"results": [
{
"id": "d3e5185a-1b7b-427c-bbe3-030bfa2e3bce",
"title": "My Book Title",
"book_content": [
{
"id": "0fea8027-3ecf-4571-a95f-5a09a93408ec",
"content": "hello content 1",
"language": "english"
},
{
"id": "0fea8027-3ecf-4571-a95f-5a09a93408ed",
"content": "你好",
"language": "chinese"
}
]
}
]
}

最佳答案

模型.py
在 BookContent 中,添加 相关姓名到外键书

class Book(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
title = models.CharField(max_length=255)

class BookContent(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='content')
content = models.TextField()
language = models.TextField()

serializers.py
引用 here欲了解更多信息
class BookContentSerializer(serializers.ModelSerializer):
class Meta:
model = BookContent
fields = ('id', 'content', 'language')

class BookSerializer(serializers.ModelSerializer):
content = BookContentSerializer(many=True, read_only=True)

class Meta:
model = Book
fields = ('id', 'title', 'content')

结果:
{
"results": [
{
"id": "d3e5185a-1b7b-427c-bbe3-030bfa2e3bce",
"title": "My Book Title",
"book_content": [
{
"id": "0fea8027-3ecf-4571-a95f-5a09a93408ec",
"content": "hello content 1",
"language": "english"
},
{
"id": "0fea8027-3ecf-4571-a95f-5a09a93408ed",
"content": "你好",
"language": "chinese"
}
]
}
]
}

关于Django REST Framework - 获取相关对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46260695/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com