I am trying to create a booking api for a website.
For this, I used perform_create function in ListCreateApiView. But, it was someone else who helped me and told me to use perform_create function.
But, I was thinking, it should be possible using create function and is a right approach rather than perform_create function.
Also, I don't really know the difference between these two functions and don't really know when to use which
Here is my code:
class BookingCreateAPIView(ListCreateAPIView):
permission_classes= [IsAuthenticated]
queryset = Booking.objects.all()
serializer_class = BookingSerializer
def perform_create(self, serializer):
# user = self.request.user
package = get_object_or_404(Package, pk= self.kwargs['pk'])
serializer.save(user=self.request.user,package=package)
Here is my serializer:
class BookingSerializer(serializers.ModelSerializer):
# blog = serializers.StringRelatedField()
class Meta:
model = Booking
fields = ['name', 'email', 'phone', 'bookedfor']
Here is my model:
class Booking(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
package = models.ForeignKey(Package, on_delete=models.CASCADE, related_name='package')
name = models.CharField(max_length=255)
email = models.EmailField()
phone = models.CharField(max_length=255)
bookedfor = models.DateField()
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ('created_at',)