Answer the question
In order to leave comments, you need to log in
How to resolve "AssertionError. The `.create()` method does not support writable nested fields by default"?
Model:
class Burger(models.Model):
name = models.CharField(max_length=64)
description = models.TextField(max_length=256)
price = models.DecimalField(max_digits=3,decimal_places=0)
class Order(models.Model):
count = models.IntegerField(default=0)
address = models.OneToOneField(Address,default='')
phone_number = models.IntegerField(default=0,blank=False)
burgers = models.ForeignKey(Burger, null=True)
class BurgerSerializer(serializers.ModelSerializer):
class Meta:
model = Burger
fields = ['name', 'description', 'price']
class OrderSerializer(serializers.ModelSerializer):
address = AddressSerializer()
burgers = BurgerSerializer(read_only=True)
class Meta:
model = Order
fields = ['count', 'phone_number', 'address', 'burgers']
class OrderList(generics.ListCreateAPIView):
# GET request to list all entrys
queryset = Order.objects.all()
serializer_class = OrderSerializer
def perform_create(self, serializer):
instance = serializer.save()
session_id = self.request.session.session_key
burger_ids = SessionOrder.objects.filter(session_id=session_id)
for item in burger_ids:
burger = Burger.objects.get(id=item.burger_id)
instance.burgers_set.add(burger)
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question