Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework: Deserializing and get the primary key from validated_data

I defined a nested model Product as follow. Each Product can belong to a lot of Productlist.

class Product(models.Model):
    product_id = models.AutoField(primary_key=True)
    product_name = models.CharField(max_length=50)

class Productlist(models.Model):
    productlist_id = models.AutoField(primary_key=True)
    productlist_name = models.CharField(max_length=50)
    product = models.ManyToManyField(Product, related_name='productlists')

The corresponding serializers are:

class ProductlistSerializer(serializers.ModelSerializer):
    class Meta:
        model = Productlist
        fields = ('productlist_id', 'productlist_name',)

class ProductSerializer(serializers.ModelSerializer):
    productlists = ProductlistSerializer(many=True, required=False)

    class Meta:
        model = Product
        fields = ('product_id', 'product_name', 'product lists')

    def create(self, validated_data):
        #some codes

When I POST a new Product (url(r'^api/products/$', views.ProductEnum.as_view()), I would like to update the product lists for adding the new product to the corresponding product lists. The JSON file I prefer to use is:

{
    "product_name": "product1"
    "productlist": [
        {
            "productlist_id": 1,
            "productlist_name": "list1",
        },
        {
            "productlist_id": 2,
            "productlist_name": list2"
        }
    ]
}

The problem is that I cannot get the productlist_id from validated_data. In Django Rest Framework, you always need to call to_internal_value() for deserializing data and generate validated_data. After some degugging, I checked the code of DRF and find the following snippets in to_internal_value():

def to_internal_value(self, data):
    """
    Dict of native values <- Dict of primitive datatypes.
    """
    if not isinstance(data, dict):
        message = self.error_messages['invalid'].format(
            datatype=type(data).__name__
        )
        raise ValidationError({
            api_settings.NON_FIELD_ERRORS_KEY: [message]
        })

    ret = OrderedDict()
    errors = OrderedDict()
    fields = [
        field for field in self.fields.values()
        if (not field.read_only) or (field.default is not empty)
    ]

    for field in fields:
        validate_method = getattr(self, 'validate_' + field.field_name, None)
        primitive_value = field.get_value(data)
        try:
            validated_value = field.run_validation(primitive_value)
            if validate_method is not None:
                validated_value = validate_method(validated_value)
        except ValidationError as exc:
            errors[field.field_name] = exc.detail
        except DjangoValidationError as exc:
            errors[field.field_name] = list(exc.messages)
        except SkipField:
            pass
        else:
            set_value(ret, field.source_attrs, validated_value)

    if errors:
        raise ValidationError(errors)

    return ret

Please notice the to_internal_value's fields has ignored the IntegerField(read_only=True) for it cannot satisfy the following condition:

        fields = [
            field for field in self.fields.values()
            if (not field.read_only) or (field.default is not empty)
        ]

So the validated_data will just have the following data:

{
    "product_name": "product1"
    "productlist": [
        {
            "productlist_name": "list1",
        },
        {
            "productlist_name": list2"
        }
    ]
}

How could I get the primary key of product list? Thanks in advance!

like image 394
Scofield77 Avatar asked Mar 17 '23 05:03

Scofield77


1 Answers

After some digging, I found that the read_only fields are only for output presentation. You can find the similar question on the offcial github link of Django REST Framework.

So the solution is overriding the read_only field in the serializer as follow:

class ProductlistSerializer(serializers.ModelSerializer):
    productlist_id = serializers.IntegerField(read_only=False)

    class Meta:
        model = Productlist
        fields = ('productlist_id', 'productlist_name',)
like image 153
Scofield77 Avatar answered Mar 19 '23 22:03

Scofield77