Django REST API适用于使用Foreignkey的模型

时间:2017-11-06 10:21:57

标签: python django django-rest-framework

我想使用DRF构建API以查看购物车。它适用于非API版本,但我在序列化程序中得到错误,该字段在模型中不存在。

models.py

class Product(models.Model):
    title = models.CharField(max_length=50, blank=False)
    cover_image = models.ImageField(upload_to='products/')
    summary = models.TextField()
    description = models.TextField()
    price = models.DecimalField(max_digits=6, decimal_places=2)
def __str__(self):
    return self.title

class Cart(models.Model):
    user = models.ForeignKey(User)
    active = models.BooleanField(default=True)
    order_date = models.DateField(null=True)
def __str__(self):
    return self.user.username

class Order(models.Model):
    product = models.ForeignKey(Product)
    cart = models.ForeignKey(Cart)
    quantity = models.IntegerField(default=1)

    def __str__(self):
        return self.product.title

views.py

def cartview(request):
    if request.user.is_authenticated():
        cart = Cart.objects.filter(user=request.user, active=True)
        orders = Order.objects.filter(cart=cart)
        total = 0
        count = 0
        for order in orders:
            total += (order.product.price * order.quantity)
            count += order.quantity
        context = {
            'total': total,
            'cart': orders,
            'count': count,
        }
        return render(request, 'store/cart.html', context)
    else:
        return redirect('index:index')

API / views.py

class CartAPIView(ListAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = CartSerializer

    def get_queryset(self, **kwargs):
        cart = Cart.objects.filter(user=self.request.user, active=True)
        orders = Order.objects.filter(cart=cart)
        total = 0
        count = 0
        for order in orders:
            total += (order.product.price * order.quantity)
            count += order.quantity
            context = {
                'total': total,
                'cart': orders,
                'count': count,
            }   
        return context

serializers.py

class CartSerializer(ModelSerializer):
    class Meta:
        model = Cart
        fields = [
                    'title',
                    'cover_image',
                    'summary',
                    'price',
                ]

我收到此错误字段名称title对模型Cart无效。

我在模板视图中获取了项目但未在api视图中获取。那我应该在这做什么呢?

1 个答案:

答案 0 :(得分:0)

您的购物车型号没有字段或方法Title,但您已将其包含在字段列表中。您只能序列化模型上存在的字段或方法,或者您创建显式链接。

您在模板中获得了产品标题,因为您已经回传了 orders = Order.objects.filter(cart=cart)。您在模板中显示的Order对象字符串方法是return self.product.title - 因此您将从订单对象转到相应的产品(连接)并获取title属性那个对象。

要在序列化程序中执行相同操作,您需要为每个对象定义一个序列化程序,然后嵌套它们。

 class CartSerializer(ModelSerializer):
    class Meta:
        model = Cart
        fields = [
                    'title',
                    'cover_image',
                    'summary',
                    'price',
                ]

class ProductSerializer(ModelSerializer):
      class Meta:
           model = Product
      ...etc... 

class OrderSerializer(ModelSerializer):
     class Meta:
          model = Order
     product = ProductSerializer
     ...etc...