Я использую Django REST Framework и использую метод .save (). Я получаю сообщение об ошибке, в котором говорится о необходимости переопределить метод .create (). Я использую несколько вложенных объектов. Я понятия не имею, как переопределить эту функцию, спасибо заранее !!
Это мой файл models.py
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
class Pizzas(models.Model):
# DB model to keep info about pizza
name = models.CharField(max_length=200)
description = models.TextField() # Ingredients n stuff
photo = models.ImageField(upload_to='main/img', default='main/img/pizza.jpg')
price = models.IntegerField(default=15)
class Meta:
verbose_name_plural = "Pizzas"
def __str__(self):
return self.name
class Orders(models.Model):
# Orders table
user = models.ForeignKey(User, on_delete=models.CASCADE) # who has ordered the pizza/pizzas
price = models.IntegerField(default=0) # Price of the orde (make a function or something to calculate this)
address = models.CharField(max_length=300) # User gives it
content = models.ManyToManyField(Pizzas) # Self explainatory
date = models.DateTimeField("Date Ordered", default=timezone.now())
class Meta:
verbose_name_plural = "Orders"
def __str__(self):
return f"{self.user} - {self.price}"
Мой файл serializers.py
from rest_framework import serializers
from main.models import Orders, Pizzas
from django.contrib.auth.models import User
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['id']
class PizzasSerializer(serializers.ModelSerializer):
class Meta:
model = Pizzas
fields = ['name']
class OrdersSerializer(serializers.ModelSerializer):
user = UserSerializer(many=True, read_only=True)
content = PizzasSerializer(many=True, read_only=True)
class Meta:
model = Orders
fields = '__all__'
А это мой API views.py
from django.shortcuts import render
from django.http import JsonResponse
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .serializers import OrdersSerializer
# Create your views here.
@api_view(['GET'])
def apiOverview(request):
api_urls = {
'Order':'/api/order'
}
return Response(api_urls)
@api_view(['POST'])
def order(request):
serializer = OrdersSerializer(data=request.data)
if serializer.is_valid():
print("Is valid, not saved yet")
serializer.save()
print("SAVED")
else:
print("it's not valid")
print(serializer.errors)
return Response(serializer.data)