Django REST框架 - 获取相关对象

时间:2017-09-17 04:37:38

标签: django django-models django-rest-framework django-views

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

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"
                }
            ]
        }
    ]
}

2 个答案:

答案 0 :(得分:1)

<强> models.py
在BookContent中,将 related_name 添加到foreignKey book

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"
                }
            ]
        }
    ]
}

答案 1 :(得分:0)

您需要为此编写查询

take a look at doc以供参考

query = BookContent.objects.filter(book=book_id)# this will give 
you a queryset with all the book content records with that particular book_id