8
votes

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?

1
Try with: p.data.get('subject', None), if this return None then 'subject' field does not exists.Gocht
@Gocht Shouldn't I be checking the validated_data though? Not the un-validated data as it may be a security risk?SilentDev
You check when you ask if is_valid()Gocht
@Gocht Hm, okay, thanks. By the way, any idea where the documentation for the .get() method is? Because I tried looking for it earlier (to see what other parameters it can take) but couldn't find it. Where does it mention that the .get() method takes a second optional parameter which is returned if the field does not exist?SilentDev

1 Answers

14
votes

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.