I want to create an order, I am trying to save a milk order by a user. Basically user has to select which type of milk they want while placing an order. What should I do in my view? I am a bit confused. The following code is giving me nothing, the data is not saving. What should I do, can anyone help please?
Here are my files. models.py
MILK_CHOICES = (
('C', 'COW'),
('B', 'BUFFALO'),
('FC', 'FULL CREAM')
)
class MilkType(models.Model):
type = models.CharField(max_length = 20, choices = MILK_CHOICES, default = MILK_CHOICES[0][1])
quantity = models.PositiveIntegerField() # Stock
description = models.CharField(max_length = 100)
class Order(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
milk_choice = models.ForeignKey(MilkType)
qty = models.PositiveIntegerField(default = 1)
serializers.py
class UserSerializer(serializers.ModelSerializer):
orders = serializers.PrimaryKeyRelatedField(many=True, queryset=Order.objects.all())
class Meta:
model = CustomUser
fields = ('id', 'username', 'email')
class MilkTypeSerializer(serializers.ModelSerializer):
class Meta:
model = MilkType
fields = ('id', 'type', 'quantity', 'description')
class OrderSerializer(serializers.ModelSerializer):
user = serializers.ReadOnlyField(source = 'user.username')
class Meta:
model = Order
fields = ('id', 'user', 'milk_choice', 'qty')
views.py
class OrderList(APIView):
def get(self, request, format = None):
orders = Order.objects.all()
serializer = OrderSerializer(orders, many = True)
return Response(serializer.data)
def post(self, request, format = None):
serializer = OrderSerializer(data = request.data)
if serializer.is_valid():
serializer.save(user = request.user)
return Response(serializer.data, status = status.HTTP_201_CREATED)
return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST)
Your code is using serializer only for validation, but it is possible use it to insert or update new objects on database calling serializer. save() . To save foreign keys using django-rest-framework you must put a related field on serializer to deal with it. Use PrimaryKeyRelatedField .
If you want to show any field of foreign key instead of id then you can use StringRelatedField.
In function-based views, we can pass extra context to serializer with “context” parameter with a dictionary. To access the extra context data inside the serializer we can simply access it with “self. context”. From example, to get “exclude_email_list” we just used code 'exclude_email_list = self.
Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.
In your OrderSerializer, define the serializer for the milk_choice
field to be the MilkTypeSerializer.
class OrderSerializer(serializers.ModelSerializer):
user = serializers.ReadOnlyField(source = 'user.username')
milk_choice = MilkTypeSerializer()
class Meta:
model = Order
fields = ('id', 'user', 'milk_choice', 'qty')
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