I am new to django and I am creating API endpoints using django rest framework.
I have created a post request so a user will fill the request body which is in json and that json will be added to the database table however the twist is that the user has to fill only a few fields and the remaining fields will be added at the server end.
For eg. lets say that the database table has fields room_number, check_in, check_out, date, capacity. The user will only fill fields check_in, check_out, date and the remaining fields will be filled at the server end.
So can someone please tell me how can I do it?
CodePudding user response:
From the document, there a few approaches to this solution:
- update serializer
In the serializer you would have something like so to modify the data before saving:
class YourModelSerializer(serializers.ModelSerializer):
class Meta:
model = YourModel
fields = ['check_in', 'check_out', 'date']
def create(self, validated_data):
validated_data['room_number'] = your_custom_value
validated_data['capacity'] = your_custom_value
return YourModel.objects.create(**validated_data)
def update(self, instance, validated_data):
instance.check_in = validated_data.get('check_in', instance.check_in)
instance.check_out = validated_data.get('check_out', instance.check_out)
instance.date = validated_data.get('date', instance.date)
instance.room_number = your_custom_value
instance.capacity = your_custom_value
instance.save()
return instance
- Passing additional attributes to .save():
Passing additional attributes to .save() Sometimes you'll want your view code to be able to inject additional data at the point of saving the instance. This additional data might include information like the current user, the current time, or anything else that is not part of the request data.
You can do so by including additional keyword arguments when calling .save(). For example:
serializer.save(room_number=your_custom_value, capacity=your_custom_value)
Any additional keyword arguments will be included in the validated_data argument when .create() or .update() are called.
- Overriding .save() directly.
In some cases the .create() and .update() method names may not be meaningful. For example, in a contact form we may not be creating new instances, but instead sending an email or other message.
In these cases you might instead choose to override .save() directly, as being more readable and meaningful.
For example:
class ContactForm(serializers.Serializer):
email = serializers.EmailField()
message = serializers.CharField()
def save(self):
email = self.validated_data['email']
message = self.validated_data['message']
send_email(from=email, message=message)
Note that in the case above we're now having to access the serializer .validated_data property directly.