Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to save data in database using django serializer

Hello I am working on a project in which I'm making serializers and I send post requests using postman. This is working fine but this is a very small part of the application and the code will grow to be very large. If there is a better way of doing this in which I write smaller code then I would like to employ that. Right now the way I'm saving the information is as follows

models.py

class Services(models.Model):
    business = models.ForeignKey(Business, on_delete=models.CASCADE)
    service = models.CharField(max_length=30, blank=True)

serializers.py

class ServiceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Services
        fields = ('id', 'business', 'service')

views.py

class ServiceAPIView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        data = request.data

        business = Business.objects.get(user=request.user)
        data['business'] = business.pk
        serializer = BusinessSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_200_OK)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

urls.py

urlpatterns = [
    path('service/', ServiceAPIView.as_view()),
]

Edited*

Here is the business model

class Business(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)

    business_name = models.CharField(max_length=50, blank=True)

    invoices_terms = models.TextField(max_length=100, blank=True)
    desc = models.TextField(max_length=1000, blank=True)

    website = models.URLField(max_length=200, blank=True)

    tax_percentage = models.DecimalField(blank=True, max_digits=5, decimal_places=3)
    labour_rate_per_hour = models.DecimalField(blank=True, max_digits=5, decimal_places=2)

    tax_hst_number = models.IntegerField(blank=True)
like image 276
ahsan mukhtar Avatar asked Sep 17 '25 03:09

ahsan mukhtar


1 Answers

Well the code looks ok and it's also ok to have deep modules.

A little update could be the following:

class ServiceAPIView(APIView):
    permission_classes = [IsAuthenticated,]
    serializer_class = ServiceSerializer
    def post(self, request):
        data = request.data
        business = Business.objects.get(user=request.user)
        data['business'] = business.pk
        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True):
        serializer.save()
        return Response(serializer.data, status=status.HTTP_200_OK)

In this way you can write only one Response line for each view request method and avoid to use if/else statements

like image 138
Trafalino Avatar answered Sep 19 '25 17:09

Trafalino