nut*_*les 3 django django-models django-views django-rest-framework
I have these models where one book can have many contents in different languages:
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()
Run Code Online (Sandbox Code Playgroud)
--------------------Update--------------------
How should i fetch Book and its related BookContent such that the result JSON looks like the following?
{
"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"
}
]
}
]
}
Run Code Online (Sandbox Code Playgroud)
models.py
在BookContent,加related_name到FOREIGNKEY书
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()
Run Code Online (Sandbox Code Playgroud)
serializers.py
请参阅此处了解更多信息
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')
Run Code Online (Sandbox Code Playgroud)
结果:
{
"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"
}
]
}
]
}
Run Code Online (Sandbox Code Playgroud)
小智 -1
你需要为此编写一个查询
查看 doc以供参考
query = BookContent.objects.filter(book=book_id)# this will give
you a queryset with all the book content records with that particular book_idRun Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1553 次 |
| 最近记录: |