Aleksei Rozhnov
Aleksei Rozhnov

Reputation: 51

Validation of the reference field in mongoengine serializer

I'm using django with mongoengine and mongoengine-rest-framework.

As shown in this article, specifying related_model_validations field in Meta class of a Serializer

class Comment(Document):
    post = ReferenceField(Post)
    owner = ReferenceField(User)
    text = StringField(max_length=140)
    isApproved = BooleanField(default=False)



from rest_framework_mongoengine import mongoengine_serializer

class CommentSerializer(MongoEngineModelSerializer):
    class Meta:
        model = Comment
        depth = 1
        related_model_validations = {'owner': User, 'post': Post}
        exclude = ('isApproved',)

can help to achieve the following result if the document referenced by the ReferenceField is missing:

{
    "owner":["User with PK ... does not exist."]
}

So instead of raising a validation exception, json is modified.

However, this article is written for the old version of mongoengine-rest-framework and in the current version there is no field related_model_validations in Serializer Meta class.

So how to achieve the similar result in the current version of the mongoengine-rest-framework?

Upvotes: 1

Views: 620

Answers (1)

Boris Burkov
Boris Burkov

Reputation: 14446

Sorry for late response, Aleksei.

Currently, if you want to PUT or POST a comment JSON, you just pass existing owner and post as their ids like:

{
    post: 2,
    user: [email protected],
    text: "Contrary to the popular belief, Karl Marx and Friedrich Engels are not a couple, but four different people"
} 

So, if you want to update Comment, Post and Author at the same time, I'm afraid, that's not possible.

In GET requests you can get related fields as nested sub-JSONs with non-zero depth argument to Serializer, as you did it in your example.

Upvotes: 0

Related Questions