0

I am building a django project using the REST framework. Data is sent through from the front end as a JSON object. I allow for null values to be accepted, and in order to facilitate this I set blank=True, null=True in the relevant places in models.py.

However, I have also used the HStoreField in order to allow arbitrary data to be stored. Now, if the value of an item inside the HStoreField is null, I get an error that:

{"arbitrary_data":["This field may not be null."]}

Is there a solution to this? From my research it looks like HStoreField has to follow a python dict structure, where the key and value are both strings. So perhaps this is the reason why I cannot set the value to null.

Doing something like this:

class Employee(models.Model):
    arbitrary_data = HStoreField(null=True, blank=True)

does not help because all it allows is for the whole HStoreField to be null.

lhay86
  • 696
  • 2
  • 5
  • 18
  • Do you use serializers? Because it looks like a serializer validation error not a model issue – Abdulafaja Sep 12 '16 at 08:39
  • Yes I do use serializers. Could you perhaps refer me to some reading to not get this error? – lhay86 Sep 12 '16 at 08:52
  • post your serializer please – arcegk Sep 12 '16 at 08:55
  • @arcegk from rest_framework import serializers from .models import Employee class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ("arbitrary_data",) – lhay86 Sep 12 '16 at 08:59
  • Serializer fields are required by default. You need to specify `arbitrary_data` explicitly and set the `required` flag to false [required flag doc](http://www.django-rest-framework.org/api-guide/fields/#required) [Specifying fields explicitly doc](http://www.django-rest-framework.org/api-guide/serializers/#specifying-fields-explicitly) – Abdulafaja Sep 12 '16 at 09:07
  • see this [answer](http://stackoverflow.com/questions/19780731/django-rest-framework-serializer-field-required-false) – arcegk Sep 12 '16 at 09:50
  • Thanks. Also I just realised that because I am using an HStoreField, I can just not send the data if the value is null. Not all keys have to be filled because it is an HStoreField – lhay86 Sep 12 '16 at 12:33

0 Answers0