Instantly share code, notes, and snippets.

Embed
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,
editable=False)
updated_at = models.DateTimeField(auto_now=True,
editable=False)
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 CommonSerializer(serializers.ModelSerializer):
"""Ensure the fields are included in the models."""
common_fields = ['created_by', 'created_at', 'updated_by', 'updated_at']
# CAVEAT 1:
# 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.
# CAVEAT 2:
# 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