Skip to content

Instantly share code, notes, and snippets.

@tysonpaul89
Last active December 28, 2021 08:33
Show Gist options
  • Select an option

  • Save tysonpaul89/1ff0ab165a2e5139eb463e70259af76b to your computer and use it in GitHub Desktop.

Select an option

Save tysonpaul89/1ff0ab165a2e5139eb463e70259af76b to your computer and use it in GitHub Desktop.
Serializer base class to implement common name validation for the child serializers.
# ===== Models =====
class Country(models.Model):
name = models.CharField(max_length=150, unique=True)
class Molecule(models.Model):
name = models.CharField(max_length=150, unique=True)
class TherapeuticCategory(models.Model):
name = models.CharField(max_length=150, unique=True)
# ===== Serializers =====
class CommonMasterDataSerializer(serializers.ModelSerializer):
"""Base class to implement common functionalities for the serializers"""
def validate_name(self, name):
queryset = self.Meta.model.objects.filter(name__iexact=name)
# In update operation exclude this model instance from the lookup
if self.instance:
queryset = queryset.exclude(id=self.instance.pk)
if queryset.exists():
raise serializers.ValidationError(
f"This {self.Meta.model._meta.verbose_name.lower()} already exists."
)
return name
class CountrySerializer(CommonMasterDataSerializer):
class Meta:
model = Country
fields = '__all__'
class MoleculeSerializer(CommonMasterDataSerializer):
class Meta:
model = Molecule
fields = '__all__'
class TherapeuticCategorySerializer(CommonMasterDataSerializer):
class Meta:
model = TherapeuticCategory
fields = '__all__'
# ===== Viewsets ========
class CountryViewSet(viewsets.ModelViewSet):
queryset = Country.objects.all().order_by('name')
serializer_class = CountrySerializer
class MoleculeViewSet(viewsets.ModelViewSet):
queryset = Molecule.objects.all().order_by('name')
serializer_class = MoleculeSerializer
class TherapeuticCategoryViewSet(viewsets.ModelViewSet):
queryset = TherapeuticCategory.objects.all().order_by('name')
serializer_class = TherapeuticCategory
# ===== URLs ========
router.register('countries', CountryViewSet)
router.register('molecule', MoleculeViewSet)
router.register('therapeutic-category', TherapeuticCategoryViewSet)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment