My model is this:
class Post(models.Model):
user = models.ForeignKey(User)
post = models.CharField(max_length=400)
subject = models.ForeignKey(Subject, blank=True, null=True)
This is my serializer:
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = ('user', 'post', 'subject')
def create(self, validated_data):
post = Post(
user = User.objects.get(username='A'),
post = validated_data['post'],
)
At this point, I want to check if 'subject' was provided by the end user, and if it was, then add the field and then save the post object (otherwise, save the post object without adding a 'subject' field). I opened up the python shell and did this:
p = PostSerializer(data={'user':16, 'post':'p'})
p.is_valid()
# returned True
if p.validated_data['subject']:
print('exists')
else:
print('does not exist')
and this returns an error saying:
Traceback (most recent call last):
File "<console>", line 1, in <module>
KeyError: 'subject'
With that said, what's the correct way of checking if a validated field exists?
We can validate the serializer by calling the method " is_valid() ". It will return the boolean(True/False) value. If the serializer is not valid then we can get errors by using the attribute "errors".
The ModelSerializer class is the same as a regular Serializer class, except that: It will automatically generate a set of fields for you, based on the model. It will automatically generate validators for the serializer, such as unique_together validators. It includes simple default implementations of .
Serializer FieldsA boolean field that accepts True, False and Null values. CharField. CharField is used to store text representation. EmailField. EmailField is also a text representation and it validates the text to be a valid e-mail address.
is_valid perform validation of input data and confirm that this data contain all required fields and all fields have correct types. If validation process succeded is_valid set validated_data dictionary which is used for creation or updating data in DB.
You can access to .data
attr from p
:
p.data.get('subject', None)
If this returns None
then 'subject' field does not exist. Data is validated when you call .is_valid()
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With