Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django-rest-framework ManyToManyField create and update

I'm new in Django, so I have a some problems. I'm using django-rest-framework. These are my model classes:

class Product(models.Model):
    name = models.CharField(max_length=100)
    price = models.FloatField()
    sizes = models.ManyToManyField(Size)
    ...
class Size(models.Model):
    name = models.CharField(max_length=100)
    ...

I would like a product serializer and a viewset that allows to create a product with its sizes.

class ProductSerializer(serializers.ModelSerializer):
    sizes = SizeSerializer(many=True)

    class Meta:
        model = Product
        fields = ('id', 'name', 'price', 'sizes')
        read_only_fields = ('id',)

The serializer written above allows to get the product with its sizes but I can't create or update the sizes of a product.

How can I attain my goal?

like image 618
fran Avatar asked Dec 25 '22 21:12

fran


1 Answers

I solved creating a serializer to get the product with nested sizes, and a serializer to create and update products using only ids.

class ProductSerializer(serializers.ModelSerializer):
    sizes = SizeSerializer(many=True) # nested objects

    class Meta:
        model = Product
        fields = ('id', 'name', 'price', 'sizes')
        read_only_fields = ('id',)


class ProductCreateUpdateSerializer(serializers.ModelSerializer):
    # no nested objects, it accepts only size ids
    class Meta:
        model = Product
        fields = ('id', 'name', 'price', 'sizes')
        read_only_fields = ('id',)

Maybe there will be some changes client-side.

like image 187
fran Avatar answered Dec 27 '22 11:12

fran