此刻,我正在学习有关Django Rest Framework的知识,我偶然发现了一个棘手的部分,我似乎无法在我们的项目中工作。我们的项目是一个虚构的网上商店,您可以在其中将爱犬婴儿放入购物车并订购。 我们的前端通过Django Rest Framework与后端进行通信。我们拥有的三个主要模型是“用户”,“订单”和“小狗”。因为每个订单都有一个幼犬列表,每个幼犬都有自己的数量,所以我们需要两者的中介模型,因为简单的ManyToManyField显然无法处理额外的列。这使事情变得更加复杂(至少对于Django新手而言)。
如何在序列化器和视图中反映关系,以及如何形成从前端发送的JSON对象?
还:
我在哪里可以计算订单总价?
即使我不想编辑或获得一个特定订单还是OrderList视图足够,我仍需要OrderDetail视图吗?
这里有一个正在解决类似问题的问题:Include intermediary (through model) in responses in Django Rest Framework 感谢Daniel Roseman的评论,我在代码中实现了它,并使它现在可以正常工作。现在可以通过/ admin手动创建订单并获取订单。 我仍然无法通过API创建订单。
这是我的代码:
models.py:
from django.db import models
from django.conf import settings
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
class Puppy(models.Model):
name = models.CharField(max_length=30)
price = models.DecimalField(max_digits=6, decimal_places=2)
image_url = models.CharField(max_length=200)
age = models.IntegerField(null=True)
weight = models.IntegerField(null=True)
description_de = models.CharField(max_length=500, null=True)
description_en = models.CharField(max_length=500, null=True)
def __str__(self):
return self.name
class Order(models.Model):
total_price = models.DecimalField(max_digits=9, decimal_places=2)
puppies = models.ManyToManyField(Puppy, through='PuppyOrder')
date = models.DateTimeField()
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='orders')
def save(self, *args, **kwargs):
"""
Create a new Order
"""
print("An order is being saved: " + str(Order.id))
super(Order, self).save(*args, **kwargs)
def __str__(self):
return str(self.id)
class PuppyOrder(models.Model):
order = models.ForeignKey(Order, on_delete=models.CASCADE)
puppy = models.ForeignKey(Puppy, on_delete=models.CASCADE)
amount = models.IntegerField()
def __str__(self):
return self.id
class Address(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
# Some more address fields ...
@receiver(post_save, sender=User)
def create_user_address(sender, instance, created, **kwargs):
if created:
Address.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_address(sender, instance, **kwargs):
instance.address.save()
views.py:
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse
from rest_framework.exceptions import ValidationError
from rest_framework_jwt.serializers import VerifyJSONWebTokenSerializer
from .serializers import UserSerializer, UserSerializerWithToken, OrderSerializer, PuppySerializer
from .permissions import IsOwner
@api_view(['GET'])
def api_root(request, format=None):
return Response({
'users': reverse('user-list', request=request, format=format),
'orders': reverse('order-list', request=request, format=format),
'puppies': reverse('puppy-list', request=request, format=format),
})
class OrderList(generics.ListCreateAPIView):
http_method_names = ["get", "post"]
queryset = Order.objects.all()
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
serializer_class = OrderSerializer
def get_queryset(self):
# Validation Code and getting self.request.user from jwt token ...
if self.request.user.is_anonymous:
return None
return Order.objects.all().filter(user=self.request.user)
def perform_create(self, serializer):
# Validation Code and getting self.request.user from jwt token ...
serializer.save(user=self.request.user)
class OrderDetail(generics.RetrieveUpdateDestroyAPIView):
http_method_names = ["get", "post"]
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
queryset = Order.objects.all()
serializer_class = OrderSerializer
class UserList(generics.ListAPIView):
http_method_names = ["get", "post"]
queryset = User.objects.all().select_related('address')
serializer_class = UserSerializer
class UserDetail(generics.RetrieveAPIView):
http_method_names = ["get", "post"]
queryset = User.objects.all().select_related('address')
serializer_class = UserSerializer
class PuppyList(generics.ListAPIView):
http_method_names = ["get"]
permission_classes = (permissions.AllowAny,)
queryset = Puppy.objects.all()
serializer_class = PuppySerializer
class PuppyDetail(generics.RetrieveAPIView):
http_method_names = ["get"]
permission_classes = (permissions.AllowAny,)
queryset = Puppy.objects.all()
serializer_class = PuppySerializer
serializers.py:
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings
from django.contrib.auth.models import User
from .models import Order, Puppy, PuppyOrder
class UserSerializer(serializers.ModelSerializer):
orders = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
class Meta:
model = User
fields = ('id', 'username', 'orders')
class UserSerializerWithToken(serializers.ModelSerializer):
# Neccessary code for generating a JWT token ...
class PuppySerializer(serializers.ModelSerializer):
description = serializers.SerializerMethodField()
def get_description(self, puppy):
return {'DE': puppy.description_de, 'EN': puppy.description_en}
class Meta:
model = Puppy
fields = ('id', 'name', 'price', 'image_url', 'age', 'weight', 'description')
class PuppyOrderSerializer(serializers.ModelSerializer):
puppy = serializers.ReadOnlyField(source='order.puppy')
order = serializers.ReadOnlyField(source='order.order')
class Meta:
model = PuppyOrder
fields = ('id', 'puppy', 'amount')
class OrderSerializer(serializers.ModelSerializer):
user = serializers.ReadOnlyField(source='user.username')
puppies = PuppyOrderSerializer(source='puppyorder_set', many=True)
# This is currently producing an error
# puppies = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
class Meta:
model = Order
fields = ('id', 'total_price', 'puppies', 'date', 'user')
请随时告诉我您是否在我的代码中看到某些可以改进或没有意义的东西。 在此先感谢您的帮助!
答案 0 :(得分:0)
通过在PuppyOrder模型中的ForeignKeys上指定related_name来破坏事物。删除那些。