Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Django classes that help you create a common model for your database.
from django.db import models
from django.conf import settings
from rest_framework import viewsets, serializers
class CommonModel(models.Model):
"""Common fields that are shared among all models."""
created_by = models.ForeignKey(settings.AUTH_USER_MODEL,
editable=False, related_name="+")
updated_by = models.ForeignKey(settings.AUTH_USER_MODEL,
editable=False, related_name="+")
created_at = models.DateTimeField(auto_now_add=True,
updated_at = models.DateTimeField(auto_now=True,
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.""", updated_by=self.request.user)
def perform_update(self, serializer):
"""Ensure we have the authorized user for ownership."""
class CommonSerializer(serializers.ModelSerializer):
"""Ensure the fields are included in the models."""
common_fields = ['created_by', 'created_at', 'updated_by', 'updated_at']
# If using a custom user model, add the following line to the top:
# from api.models.user_profile import User # noqa: F401
# It's needed for get_model in settings.
# All api calls that add or edit a line to your database should be Authenticated.
# If you're not doing that then you are ASKING for trouble.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.