Reputation: 1414
I have a simple model that is serialized and created. The Viewset for this is as follows:
class OrderViewset(viewsets.ModelViewSet):
depth = 1
serializer_class = OrderSerializer
...
def perform_create(self, serializer):
serializer.save(user=self.request.user)
populate_ing(serializer)
Once the user saves and creates the model, I aim to shoot of and call 'populate_ing(xxx)' which takes the model (in this case an order) and creates a number of related objects using a foreign key relationship.
Is it possible to handle this on save? Believe, as above, by overriding the perform_create I should do so. And, most importantly, how can I access the model which has just been created?
For more explicit of what I am after, I would hope to do the following:
My serializer is as follows:
class OrderSerializer(serializers.ModelSerializer):
class Meta:
model = Order
fields = '__all__'
In a normal Djnago view with a form, I would handle it something to the effect of:
def view_create_order(request):
form = OrderForm(request.POST or None)
if form.is_valid():
new_order = form.save()
populate_ing(new_order)
context = {"form": form}
template = "order/order-update.html"
return render(request, template, context)
Upvotes: 0
Views: 318
Reputation: 88519
The created instance will be available in instance
attribute, so it can be pass to the populate_ing()
function as,
class OrderViewset(viewsets.ModelViewSet):
# depth = 1
serializer_class = OrderSerializer
...
def perform_create(self, serializer):
serializer.save(user=self.request.user)
populate_ing(serializer.instance)
Upvotes: 2