сериализация не работает должным образом на более низких уровнях - django-rest-framework - PullRequest
0 голосов
/ 01 апреля 2019

моя Comment модель, как показано ниже:

class Comment(models.Model):
    user = models.ForeignKey(User)
    content = models.TextField()
    parent = models.ForeignKey('self', related_name='answers')

Я хочу комментировать сериализатор и все его ответы. Итак, я написал этот сериализатор:

class CommentSerializer(ModelSerializer):

    user = UserSerializer(fields=('get_full_name',), allow_null=True)

    class Meta:
        model = Comment
        fields = ['user', 'content', 'answers']
        depth = 10

теперь, когда я сериализирую комментарий этим сериализатором, он работает правильно только для уровня 1 комментария. объект answers показывает все данные, такие как пароль пользователя! или он показывает 'parent', пока я не включил parent в класс fields из Meta сериализатора. следующий вывод этого сериализатора:

{
"data": {
    "pk": 15,
    "user": null,
    "name": "rwqerweqr",
    "email": null,
    "content": "A",
    "approved": false,
    "created_at": "2019-03-31T23:16:44.980338+04:30",
    "answers": [
        {
            "id": 14,
            "content": "B",
            "name": null,
            "email": null,
            "approved": false,
            "created_at": "2019-03-31T23:08:13.374350+04:30",
            "user": {
                "id": 3,
                "is_superuser": true,
                "email": "email@gmail.com",
                "phone": "+111111111111",
                "password": "pbkdf2_sha256$36000$RDdFKTXhvzhb$GaR2Y0p1DBp/5pO5yqayMmdNN/XjnoWEdKshYbmkwCk=",
                "first_name": "Alex",
                "last_name": "Doe",
                "created_at": "2019-03-26T21:16:53.818407+04:30",
                "last_login": "2019-03-26T21:17:14.987512+04:30",
                "is_active": true,
                "is_staff": true,
                "groups": [],
                "user_permissions": []
            },
            "parent": {
                "id": 15,
                "content": "A",
                "name": "rwqerweqr",
                "email": null,
                "approved": false,
                "created_at": "2019-03-31T23:16:44.980338+04:30",
                "user": null,
                "parent": {
                    "id": 13,
                    "content": "C",
                    "name": null,
                    "email": null,
                    "approved": false,
                    "created_at": "2019-03-31T21:27:29.152248+04:30",
                    "user": {
                        "id": 3,
                        "is_superuser": true,
                        "email": "email@gmail.com",
                        "phone": "+111111111111",
                        "password": "pbkdf2_sha256$36000$RDdFKTXhvzhb$GaR2Y0p1DBp/5pO5yqayMmdNN/XjnoWEdKshYbmkwCk=",
                        "first_name": "Alex",
                        "last_name": "Doe",
                        "created_at": "2019-03-26T21:16:53.818407+04:30",
                        "last_login": "2019-03-26T21:17:14.987512+04:30",
                        "is_active": true,
                        "is_staff": true,
                        "groups": [],
                        "user_permissions": []
                    },
                    "parent": {
                        "id": 14,
                        "content": "B",
                        "name": null,
                        "email": null,
                        "approved": false,
                        "created_at": "2019-03-31T23:08:13.374350+04:30",
                        "user": {
                            "id": 3,
                            "is_superuser": true,
                            "email": "email@gmail.com",
                            "phone": "+111111111111",
                            "password": "pbkdf2_sha256$36000$RDdFKTXhvzhb$GaR2Y0p1DBp/5pO5yqayMmdNN/XjnoWEdKshYbmkwCk=",
                            "first_name": "Alex",
                            "last_name": "Doe",
                            "created_at": "2019-03-26T21:16:53.818407+04:30",
                            "last_login": "2019-03-26T21:17:14.987512+04:30",
                            "is_active": true,
                            "is_staff": true,
                            "groups": [],
                            "user_permissions": []
                        },
                        "parent": {
                            "id": 15,
                            "content": "A",
                            "name": "rwqerweqr",
                            "email": null,
                            "approved": false,
                            "created_at": "2019-03-31T23:16:44.980338+04:30",
                            "user": null,
                            "parent": {
                                "id": 13,
                                "content": "C",
                                "name": null,
                                "email": null,
                                "approved": false,
                                "created_at": "2019-03-31T21:27:29.152248+04:30",
                                "user": {
                                    "id": 3,
                                    "is_superuser": true,
                                    "email": "email@gmail.com",
                                    "phone": "+111111111111",
                                    "password": "pbkdf2_sha256$36000$RDdFKTXhvzhb$GaR2Y0p1DBp/5pO5yqayMmdNN/XjnoWEdKshYbmkwCk=",
                                    "first_name": "Alex",
                                    "last_name": "Doe",
                                    "created_at": "2019-03-26T21:16:53.818407+04:30",
                                    "last_login": "2019-03-26T21:17:14.987512+04:30",
                                    "is_active": true,
                                    "is_staff": true,
                                    "groups": [],
                                    "user_permissions": []
                                },
                                "parent": {
                                    "id": 14,
                                    "content": "B",
                                    "name": null,
                                    "email": null,
                                    "approved": false,
                                    "created_at": "2019-03-31T23:08:13.374350+04:30",
                                    "user": {
                                        "id": 3,
                                        "is_superuser": true,
                                        "email": "email@gmail.com",
                                        "phone": "+111111111111",
                                        "password": "pbkdf2_sha256$36000$RDdFKTXhvzhb$GaR2Y0p1DBp/5pO5yqayMmdNN/XjnoWEdKshYbmkwCk=",
                                        "first_name": "Alex",
                                        "last_name": "Doe",
                                        "created_at": "2019-03-26T21:16:53.818407+04:30",
                                        "last_login": "2019-03-26T21:17:14.987512+04:30",
                                        "is_active": true,
                                        "is_staff": true,
                                        "groups": [],
                                        "user_permissions": []
                                    },
                                    "parent": {
                                        "id": 15,
                                        "content": "A",
                                        "name": "rwqerweqr",
                                        "email": null,
                                        "approved": false,
                                        "created_at": "2019-03-31T23:16:44.980338+04:30",
                                        "user": null,
                                        "parent": {
                                            "id": 13,
                                            "content": "C",
                                            "name": null,
                                            "email": null,
                                            "approved": false,
                                            "created_at": "2019-03-31T21:27:29.152248+04:30",
                                            "user": {
                                                "id": 3,
                                                "is_superuser": true,
                                                "email": "email@gmail.com",
                                                "phone": "+111111111111",
                                                "password": "pbkdf2_sha256$36000$RDdFKTXhvzhb$GaR2Y0p1DBp/5pO5yqayMmdNN/XjnoWEdKshYbmkwCk=",
                                                "first_name": "Alex",
                                                "last_name": "Doe",
                                                "created_at": "2019-03-26T21:16:53.818407+04:30",
                                                "last_login": "2019-03-26T21:17:14.987512+04:30",
                                                "is_active": true,
                                                "is_staff": true,
                                                "groups": [],
                                                "user_permissions": []
                                            },
                                            "parent": {
                                                "id": 14,
                                                "content": "B",
                                                "name": null,
                                                "email": null,
                                                "approved": false,
                                                "created_at": "2019-03-31T23:08:13.374350+04:30",
                                                "user": 3,
                                                "parent": 15
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        },
        {
            "id": 16,
            "content": "D",
            "name": "werwer",
            "email": null,
            "approved": false,
            "created_at": "2019-04-01T18:37:46.981327+04:30",
            "user": null,
            "parent": {
                "id": 15,
                "content": "A",
                "name": "rwqerweqr",
                "email": null,
                "approved": false,
                "created_at": "2019-03-31T23:16:44.980338+04:30",
                "user": null,
                "parent": {
                    "id": 13,
                    "content": "C",
                    "name": null,
                    "email": null,
                    "approved": false,
                    "created_at": "2019-03-31T21:27:29.152248+04:30",
                    "user": {
                        "id": 3,
                        "is_superuser": true,
                        "email": "email@gmail.com",
                        "phone": "+111111111111",
                        "password": "pbkdf2_sha256$36000$RDdFKTXhvzhb$GaR2Y0p1DBp/5pO5yqayMmdNN/XjnoWEdKshYbmkwCk=",
                        "first_name": "Alex",
                        "last_name": "Doe",
                        "created_at": "2019-03-26T21:16:53.818407+04:30",
                        "last_login": "2019-03-26T21:17:14.987512+04:30",
                        "is_active": true,
                        "is_staff": true,
                        "groups": [],
                        "user_permissions": []
                    },
                    "parent": {
                        "id": 14,
                        "content": "B",
                        "name": null,
                        "email": null,
                        "approved": false,
                        "created_at": "2019-03-31T23:08:13.374350+04:30",
                        "user": {
                            "id": 3,
                            "is_superuser": true,
                            "email": "email@gmail.com",
                            "phone": "+111111111111",
                            "password": "pbkdf2_sha256$36000$RDdFKTXhvzhb$GaR2Y0p1DBp/5pO5yqayMmdNN/XjnoWEdKshYbmkwCk=",
                            "first_name": "Alex",
                            "last_name": "Doe",
                            "created_at": "2019-03-26T21:16:53.818407+04:30",
                            "last_login": "2019-03-26T21:17:14.987512+04:30",
                            "is_active": true,
                            "is_staff": true,
                            "groups": [],
                            "user_permissions": []
                        },
                        "parent": {
                            "id": 15,
                            "content": "A",
                            "name": "rwqerweqr",
                            "email": null,
                            "approved": false,
                            "created_at": "2019-03-31T23:16:44.980338+04:30",
                            "user": null,
                            "parent": {
                                "id": 13,
                                "content": "C",
                                "name": null,
                                "email": null,
                                "approved": false,
                                "created_at": "2019-03-31T21:27:29.152248+04:30",
                                "user": {
                                    "id": 3,
                                    "is_superuser": true,
                                    "email": "email@gmail.com",
                                    "phone": "+111111111111",
                                    "password": "pbkdf2_sha256$36000$RDdFKTXhvzhb$GaR2Y0p1DBp/5pO5yqayMmdNN/XjnoWEdKshYbmkwCk=",
                                    "first_name": "Alex",
                                    "last_name": "Doe",
                                    "created_at": "2019-03-26T21:16:53.818407+04:30",
                                    "last_login": "2019-03-26T21:17:14.987512+04:30",
                                    "is_active": true,
                                    "is_staff": true,
                                    "groups": [],
                                    "user_permissions": []
                                },
                                "parent": {
                                    "id": 14,
                                    "content": "B",
                                    "name": null,
                                    "email": null,
                                    "approved": false,
                                    "created_at": "2019-03-31T23:08:13.374350+04:30",
                                    "user": {
                                        "id": 3,
                                        "is_superuser": true,
                                        "email": "email@gmail.com",
                                        "phone": "+111111111111",
                                        "password": "pbkdf2_sha256$36000$RDdFKTXhvzhb$GaR2Y0p1DBp/5pO5yqayMmdNN/XjnoWEdKshYbmkwCk=",
                                        "first_name": "Alex",
                                        "last_name": "Doe",
                                        "created_at": "2019-03-26T21:16:53.818407+04:30",
                                        "last_login": "2019-03-26T21:17:14.987512+04:30",
                                        "is_active": true,
                                        "is_staff": true,
                                        "groups": [],
                                        "user_permissions": []
                                    },
                                    "parent": {
                                        "id": 15,
                                        "content": "A",
                                        "name": "rwqerweqr",
                                        "email": null,
                                        "approved": false,
                                        "created_at": "2019-03-31T23:16:44.980338+04:30",
                                        "user": null,
                                        "parent": {
                                            "id": 13,
                                            "content": "C",
                                            "name": null,
                                            "email": null,
                                            "approved": false,
                                            "created_at": "2019-03-31T21:27:29.152248+04:30",
                                            "user": {
                                                "id": 3,
                                                "is_superuser": true,
                                                "email": "email@gmail.com",
                                                "phone": "+111111111111",
                                                "password": "pbkdf2_sha256$36000$RDdFKTXhvzhb$GaR2Y0p1DBp/5pO5yqayMmdNN/XjnoWEdKshYbmkwCk=",
                                                "first_name": "Alex",
                                                "last_name": "Doe",
                                                "created_at": "2019-03-26T21:16:53.818407+04:30",
                                                "last_login": "2019-03-26T21:17:14.987512+04:30",
                                                "is_active": true,
                                                "is_staff": true,
                                                "groups": [],
                                                "user_permissions": []
                                            },
                                            "parent": {
                                                "id": 14,
                                                "content": "B",
                                                "name": null,
                                                "email": null,
                                                "approved": false,
                                                "created_at": "2019-03-31T23:08:13.374350+04:30",
                                                "user": 3,
                                                "parent": 15
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    ]
}
}

Как видите, в объекте answers он полностью отображает данные пользователя, включая его хешированный пароль или разрешения. или показывает поле parent, когда его вообще нет в сериализаторе!.

как решить эту проблему? спасибо.

UPDATE
сценарий использования: Комментарии B и D являются ответами на комментарий A. (b.parent == A)

1 Ответ

0 голосов
/ 02 апреля 2019

Как показано в django-rest-framework документах:

Для параметра глубины должно быть установлено целочисленное значение, которое указывает глубину отношений, которые необходимо пройти, прежде чем вернуться к плоскому представлению.

Если вы хотите настроить способ сериализации, вам нужно определить поле самостоятельно.

Вы должны сериализовать поле answers, чтобы скрыть эту информацию. Я бы следовал подходу SerializerMethodField. Я напишу пример:

class CommentSerializer(ModelSerializer):

    user = UserSerializer(fields=('get_full_name',), allow_null=True)
    answers = serializers.SerializerMethodField()

    class Meta:
        model = Comment
        fields = ['user', 'content', 'answers']

    def get_answers(self, instance):
        # Here you will create your custom serialization
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...