Django Serlizing多个与foreginkey相关的模型

时间:2019-06-23 06:40:59

标签: django django-rest-framework

我无法在api端点中显示交叉关系数据

这是我的Serser类:

class ArticleSerializer(serializers.ModelSerializer):
    # these two variables are assigned coz, author and category are foregin key
    author = serializers.StringRelatedField()
    category = serializers.StringRelatedField()

    class Meta:
        model =  Article
        fields = '__all__'

以上序列化工作正常,但不能满足需求。

这是我的模特

from django.db import models
import uuid

class Organization(models.Model):
    organization_name = models.CharField(max_length=50)
    contact = models.CharField(max_length=12, unique=True)

    def __str__(self):
        return self.organization_name

class Author(models.Model):
    name = models.CharField(max_length=40)
    detail = models.TextField()
    organization = models.ForeignKey(Organization, on_delete=models.DO_NOTHING)

    def __str__(self):
        return self.name

class Category(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

class Article(models.Model):
    alias = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='author')
    title = models.CharField(max_length=200)
    body = models.TextField()
    category = models.ForeignKey(Category, on_delete=models.CASCADE)

这是我的观点

class ArticleSingle(RetrieveAPIView):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer
    lookup_field = 'alias'

,目前我的端点显示如下,但我不喜欢

HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

{
    "alias": "029a4b50-2e9a-4d35-afc6-f354d2169c05",
    "author": "jhon doe",
    "category": "sic-fi",
    "title": "title goes here",
    "body": "this is body"
}

我希望端点显示带有作者详细信息的数据,例如authororganization_namecontact等(如果您不了解的话),请查看我的模型如何设计它。

端点应该显示每个带有外键的相关数据,希望您能解决我的问题,谢谢您的宝贵时间

1 个答案:

答案 0 :(得分:1)

您正在寻找的是 nested serialization

应该将它们分配为序列化器类(而不是将authorcategory指定为StringRelatedFields(对Organization模型也是如此)

class OrganizationSerializer(serializers.ModelSerializer):
    ...

    class Meta:
        model = Organization
        fields = '__all__'


class AuthorSerializer(serializers.ModelSerializer):
    organization = OrganizationSerializer()
    ...

    class Meta:
        model = Author
        fields = '__all__'


class CategorySerializer(serializers.ModelSerializer):
    ...

    class Meta:
        model = Category
        fields = '__all__'


class ArticleSerializer(serializers.ModelSerializer):
    author = AuthorSerializer()
    category = CategorySerializer()

    class Meta:
        model =  Article
        fields = '__all__'

此机制将根据需要序列化数据:

HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

{
    "alias": "029a4b50-2e9a-4d35-afc6-f354d2169c05",
    "author": {
        "name": "jhon doe",
        "organization": {
            "organization_name": "..."
        }
        ...
    }
    "category": {
         "name": "sic-fi"
    }
    "title": "title goes here",
    "body": "this is body"
}

注意:如果要执行POST请求以创建这些资源,则可以找到一些有用的信息here