Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DjangoRestFramework - How do I check if an optional serializer field exists in valiated_data?

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?

like image 559
SilentDev Avatar asked Oct 06 '15 22:10

SilentDev


People also ask

How do I know if my serializer is valid?

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".

What is difference between serializer and ModelSerializer?

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 .

What is serializer field?

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.

What does serializer Is_valid do?

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.


1 Answers

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.

like image 98
Gocht Avatar answered Sep 19 '22 08:09

Gocht