So I have a modelserializer that creates a new model instance in case of post requests to an endpoint.
How can I grab the newly created instance in the view for further processing? (I need the id of the new instance for a related model).
# serializers.py
class OfferList(APIView):
"""
List all Offers or create a new Offer related to the authenticated user
"""
def get(self, request):
offers = Offer.objects.filter(company__userprofile__user=request.user)
serializer = OfferSerializer(offers, many=True)
return Response(serializer.data)
def post(self, request):
serializer = OfferSerializer(data=request.data)
if serializer.is_valid():
# Get the related company instance
company = get_object_or_404(Company, userprofile__user=request.user)
# Pass the related instance to the serializer instance to save the new Offer instance
serializer.save(company=company)
# Create Payment instances - returns a dict
payments = create_payments(
serializer.data.get('start_salary'),
serializer.data.get('months'),
serializer.data.get('start_date'),
serializer.data.get('interest_type'),
serializer.data.get('interest_interval'),
serializer.data.get('interest_raise')
)
# Loop the dict and generate instances
for key, value in payments.items():
Payment.objects.create(
offer= , # how to access the id of the created instance by the serializer above?
month=key,
amount=value
)
return Response(serializer.data,
status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# models.py
class Payment(models.Model):
"""
A table to store all payments derived from an offer.
"""
# Each monthly payment relates to an offer
offer = models.ForeignKey(Offer, on_delete=models.CASCADE)
month = models.DateField()
amount = models.PositiveIntegerField()
CodePudding user response:
As the django-rest-framework docs says,
If your object instances correspond to Django models you'll also want to ensure that these methods save the object to the database. Now when deserializing data, we can call
.save()
to return an object instance, based on the validated data.
Calling.save()
will either create a new instance, or update an existing instance, depending on if an existing instance was passed when instantiating the serializer class.
So you can do the following to grab the newly created instance:
instance = serializer.save(company=company)