B
B
bubaley2020-05-02 12:59:32
Django
bubaley, 2020-05-02 12:59:32

How do I properly create objects in django using drf?

Model:

class ProjectInvite(models.Model):
    project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='project_invites')
    from_user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name='sended_project_invites')
    to_user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name='came_project_invites')

Serializer:
class ProjectInviteSerializer(serializers.ModelSerializer):
    from_user = UserSerializer(many=False, read_only=True)
    to_user = UserSerializer(many=False)
    project = ProjectSerializer(many=False)

    class Meta:
        model = models.ProjectInvite
        fields = ('id', 'from_user', 'to_user', 'project')

View:
class ProjectInviteViewSet(viewsets.ModelViewSet):
    serializer_class = serializers.ProjectInviteSerializer
    queryset = models.ProjectInvite.objects

    def perform_create(self, serializer):
        serializer.save(from_user=self.request.user)


Prompt Good Practice for creation of Such objects. Options:
1. Use WritableNestedModelSerializer. But then he requires to transfer the entire structure of the project, which is not very desirable to do.
2. Override the ViewSet - create method. If possible, I would like an example for this paragraph.
3. Write an ApiView with one method and use it to create it, in which I will manually receive objects, and leave the logic for receiving a list and viewing an element in the ViewSet.
Tell me how this can be implemented or maybe there is the most optimal option that I don’t even know about.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question