【问题标题】:Serializer Nested relationships not working as it sholuld be序列化器嵌套关系无法正常工作
【发布时间】:2018-02-09 18:46:39
【问题描述】:

嵌套关系 django 1.11

序列化器:

class PostDetailSerializer(ModelSerializer):
    url = post_detail_url
    user = UserSerializer(read_only=True)
    image = SerializerMethodField()
    html = SerializerMethodField()
    tags = TagSerializer(many=True)
    category = CategorySerializer()
    source = SourceSerializer()

    class Meta:
        model = Post
        fields = [
            'id',
            'url',
            'title',
            'image',
            'slug',
            'content',
            'source',
            'source_link',
            'category',
            'tags',
            'html',
            'publish',
            'timestamp',
            'user',
        ]

回复:

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

{
    "id": 3,
    "url": "http://127.0.0.1:8000/api/v1/posts/new-postas/",
    "title": "New Postaas",
    "image": null,
    "slug": "new-postas",
    "content": "asssaasssasa",
    "source": {
    "id": 1,
    "name": "prothom alo",
    "slug": "prothom-alo"
    },
    "source_link": "http://prothom-alo.com/",
    "category": {
        "id": 2,
        "url": "http://127.0.0.1:8000/api/v1/posts/category/news/",
        "name": "news"
    },
    "tags": [
        {
            "id": 1,
            "name": "tech",
            "slug": "tech"
        }
    ],
    "html": "<p>asssaasssasa</p>\n",
    "publish": "2017-08-31",
    "timestamp": "2017-08-31T12:28:28.686538Z",
    "user": {
        "id": "ac32460f-fb7e-4755-9f7e-7c13085ee92b",
        "email": "hello@ihemel.net",
        "first_name": "Hasibul Amin",
        "last_name": "Hemel"
    }
}

这是检索数据的精细嵌套关系。

但再次在我的类别详细信息 api 序列化器下面:

class CategoryDetailSerializer(ModelSerializer):
    url = category_detail_url
    posts = PostDetailSerializer(many=True, read_only=True)

    class Meta:
        model = Category
        fields = [
            'id',
            'url',
            'name',
            'posts'
        ]

这里我的 post 序列化器不会在 api 中输出任何数据。我不知道。没有错误或错误,只是价值没有到来。

分类详情api响应:

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

{
    "id": 2,
    "url": "http://127.0.0.1:8000/api/v1/posts/category/news/",
    "name": "news"
}

有什么解决办法吗?我搜索了但没有找到。

【问题讨论】:

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


    【解决方案1】:

    由于您在CategoryDetailSerializer 中使用字段名posts,因此您需要将related_name=posts 设置为Post 模型中的类别关系:

    class Post(Model):
        category = ForeignKey(Category, related_name='posts')
    

    或者您可以在CategoryDetailSerializer 中使用默认关系名称post_set:

    class CategoryDetailSerializer(ModelSerializer):
        url = category_detail_url
        post_set = PostDetailSerializer(many=True, read_only=True)
    
        class Meta:
            model = Category
            fields = [
            'id',
            'url',
            'name',
            'post_set'
            ]
    

    查看详情here。

    您也可以尝试使用模型中的 related_name 在序列化器字段上指定源:

    posts = PostDetailSerializer(many=True, read_only=True, source='cat_posts')
    

    【讨论】:

    • 你好,我把这个放在模型上。category = models.ForeignKey(Category, related_name='cat_posts', default=1) tags = models.ManyToManyField(Tags, related_name='rel_posts', help_text="Select tags for this review") 用于类别和标签。我应该将类别related_name 更改为posts 吗?但为什么?不应该posts以外的其他行不行?我只是不明白。你能描述一下吗?谢谢。
    • @Hemel 来自文档:You'll normally want to ensure that you've set an appropriate related_name argument on the relationship, that you can use as the field name. 因此,如果您有相关名称,则还需要在序列化程序中使用此名称。或者您可以尝试在posts 字段上设置源:posts = PostDetailSerializer(many=True, read_only=True, source='cat_posts')。
    • 那么post_set 将如何工作而不是posts?如果在您给定的示例模型中related_name 是posts?
    • posts_set 仅在您不使用related_name 时才有效。因此,在您的情况下,这不是解决方案。尝试source 参数,如果这不起作用,请将序列化程序中的字段重命名为cat_posts。
    • 我只是将 posts 更改为 cat_postsin CategoryDetailSerializer ,它的工作原理。很遗憾,我无法得到它:) 谢谢你的帮助。
    【解决方案2】:

    我认为 CategoryDe​​tailSerializer() 不会被调用, 调用的是另一个 Category 序列化器,即 CategorySerializer()。

    【讨论】:

    • 我从它被调用的 url 中检查了一下。 url(r'^category/(?P&lt;slug&gt;[\w-]+)/$', CategoryDetailAPIView.as_view(), name='category-detail'), 和查看代码。 class CategoryDetailAPIView(RetrieveAPIView): queryset = Category.objects.all() serializer_class = CategoryDetailSerializer lookup_field = 'slug' permission_classes = [AllowAny]@theShakelProgrammer
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-03
    • 1970-01-01
    • 2014-05-13
    • 1970-01-01
    • 1970-01-01
    • 2018-07-04
    • 2011-06-01
    相关资源
    最近更新 更多