quantifiedcode / python-anti-patterns

An open collection of Python anti-patterns and worst practices.
https://quantifiedcode.github.io/python-anti-patterns
Other
1.71k stars 249 forks source link

double save #97

Open Lewiscowles1986 opened 7 years ago

Lewiscowles1986 commented 7 years ago

Not sure if this can be integrated, but it would be nice to see it as it's one of the most common things I encounter across a range of technologies (not just python or django)

So I recently saw this in some django code (I've made it generic)

class ItemViewSet(viewsets.ModelViewSet):
    queryset = models.Item.objects.all()
    serializer_class = ItemSerializer

    def perform_create(self, serializer):
        instance = serializer.save()
        instance.url = reverse('item-detail', args=[instance.pk], request=self.request)
        instance.save()

This causes a double-save to a single instance, which IMO is never acceptable and a sign of a bad design.

Instead I recommend adding this to ItemSerializer (basically generating every time before sending to view)

class ItemSerializer(HyperlinkedModelSerializer):
    url = HyperlinkedIdentityField(view_name='item-detail', read_only=True)