Home > front end >  Common models in Django Rest Framework
Common models in Django Rest Framework

Time:11-11

I found this very useful article how to use common models in the DRF. Common Models in Django and the DRF

So I wanted to have a create_by, created_when, updated_by and updated_when attribute for all by objects in the database. I used the viewsets.ModelViewSet together with mixins.ListModelMixin and mixins.CreateModelMixin before and it worked. I just replaced the viewsets.ModelViewSet with my new CommonViewSet class.

This is my code:

views.py

class CommonViewSet(viewsets.ModelViewSet):
"""Ensure the models are updated with the requesting user."""

    def perform_create(self, serializer):
        """Ensure we have the authorized user for ownership."""
        serializer.save(created_by=self.request.user, updated_by=self.request.user)

    def perform_update(self, serializer):
        """Ensure we have the authorized user for ownership."""
        serializer.save(updated_by=self.request.user)


class TagViewSet(CommonViewSet,
             mixins.ListModelMixin,
             mixins.CreateModelMixin):
    """Manage tags in the database"""
    authentication_classes = (TokenAuthentication,)
    permission_classes = (IsAuthenticated,)
    queryset = Tag.objects.all()
    serializer_class = serializers.TagSerializer

serializers.py

class CommonSerializer(serializers.ModelSerializer):
"""Ensure the fields are included in the models."""

common_fields = ['created_by', 'created_at', 'updated_by', 'updated_at']


class TagSerializer(CommonSerializer):
    """Serializer for tag objects"""

    class Meta:
        model = Tag
        fields = (['id', 'name']   CommonSerializer.common_fields)
        read_only_fields = ('id',)

models.py

class CommonModel(models.Model):
"""Common fields that are shared among all models."""

created_by = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.PROTECT,
                               editable=False, related_name=" ")
updated_by = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.PROTECT,
                               editable=False, related_name=" ")
created_at = models.DateTimeField(auto_now_add=True,
                                  editable=False)
updated_at = models.DateTimeField(auto_now=True,
                                  editable=False)

class Tag(CommonModel):
"""Tag to be used for device type"""
name = models.CharField(max_length=255)

def __str__(self):
    return self.name

But now I get this error message:

class TagViewSet(CommonViewSet, TypeError: Cannot create a consistent method resolution order (MRO) for bases CreateModelMixin, ListModelMixin

CodePudding user response:

The DRF ModelViewseT Written as follows

class ModelViewSet(mixins.CreateModelMixin,
                   mixins.RetrieveModelMixin,
                   mixins.UpdateModelMixin,
                   mixins.DestroyModelMixin,
                   mixins.ListModelMixin,
                   GenericViewSet):

So in TagViewSet, You don't need to import mixins again. You can write this as follows

class TagViewSet(CommonViewSet):
    ...
  • Related