Django-rest-framework - Equivalent to "perform_create" in APIView

Where can I set the associated model when I create an object in APIView

?

def perform_create(self, serializer): 
     serializer.save(owner=self.request.user)

      

The above works in generics.ListAPIView

, but what about APIView

? I have two models A

and B

. B

has ForeignKey

- A

. When instantiated, B

how to set ForeignKey

before saving?

a = A.objects.get(id=request.DATA['a_id'])
serializer = BSerializer(data=request.DATA)

     if serializer.is_valid():
           b = serializer.save(a=a)

      

If I include a box A

in BSerializer

, it complains that a This field is required

. If I exclude him, he will give IntegrityError

. How should this be done?

+3


source to share


1 answer


For Django REST Framework 3.0:

perform_create

is available through the generic API, so it works for GenericAPIView

any subclass as well (including instances ViewSet

).

The error you are getting is at the serializer level before you reach the point serializer.save

, so having perform_create

it will not help you fully. If the user never presents a fully nested representation of the object (and your serializer expects one), then your best bet is to make the field read_only

and process it outside of the serializer by passing it to serializer.save

.

For Django REST Framework 2.4:

perform_create

is new in Django REST Framework 3.0, so the current documentation does not match the version you are using. If you can upgrade to Django REST Framework 3.0, it is recommended to do so.



In Django REST Framework 2.4, the serializer contains a reference to the model object that is created or modified in an attribute serializer.object

. For ModelSerializer

this, it is a model object with any changes that were submitted (provided that it passed the validation). The call serializer.save

just saves that object (when rebuilding the relationship), so you can modify it directly.

To establish a foreign key relationship that is required when an object is saved or created, you just need to do ...

serializer.object.related_field = related_object

      

... before the call serializer.save()

(no arguments). In Django REST Framework 2.4, any arguments passed to serializer.save

are reduced to model.save

, so you cannot use the method recommended for Django REST Framework 3.0. In 3.0, serializer.save

it allows additional arguments to be passed to be set directly to the object to be created (the best way to set it serializer.validated_data

), instead of passing them to model.save

.

+9


source







All Articles