Reputation: 22757
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?
Upvotes: 10
Views: 10201
Reputation: 10256
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.
Upvotes: 16