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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With