Verify model field changed / exclude specific instances from queryset / provide custom 'queryset' to PrimaryKeyRelatedField / request.data vs request.body

JunePyo Suh·2020년 9월 22일
0
post-custom-banner

Verify model field changed

Check self._state of the model.
self._state.adding is True when the model is being created.
self._state.adding is False when the model is being updated.

Exclude specific instances from queryset

Model-agnostic way of excluding:
query.exclude(pk=instance.pk)

using in with list comprehension:
query.exclude(id__in=[o.id for o in <unwanted objects>])

provide custom 'queryset' to PrimaryKeyRelatedField

subclass PrimaryKeyRelatedField and overload the get_queryset method

class UserFilteredPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField):
    def get_queryset(self):
        request = self.context.get('request', None)
        queryset = super(UserFilteredPrimaryKeyRelatedField, self).get_queryset()
        if not request or not queryset:
            return None
        return queryset.filter(user=request.user)

// In serializers.py
class MySerializer(serializers.ModelSerializer):
    related = UserFilteredPrimaryKeyRelatedField(queryset=MyModel.objects)

request.data (DRF) vs request.body (pure Django)

Quoting the docs:
request.data:

REST framework introduces a Request object that extends the regular HttpRequest, and provides more flexible request parsing. The core functionality of the Request object is the request.data attribute, which is similar to request.POST, but more useful for working with Web APIs.
request.POST : Only handles form data. Only works for 'POST' method.
request.data : Handles arbitrary data. Works for 'POST', 'PUT' and 'PATCH' methods.

request.body:

The raw HTTP request body as a byte string. This is useful for processing data in different ways than conventional HTML forms: binary images, XML payload etc. For processing conventional form data, use HttpRequest.POST.

In short, request.body is simply the body of the request. request.data is a fully parsed body (ex - python dict) that is more convenient to handle.

Blog on working with request.data in DRF

post-custom-banner

0개의 댓글