Django-Rest-Framework-以反向关系使用外键

时间:2018-02-25 09:52:31

标签: python django serialization django-rest-framework foreign-keys

models.py

class ProductsDescription(models.Model):
    category = models.CharField(max_length=255)
    name = models.CharField(max_length=255)
    price = models.DecimalField(max_digits=255,decimal_places=2)
    description = models.TextField()
    specification = models.TextField()
    photos = models.URLField()

class Cart(models.Model):
    UserId = models.PositiveIntegerField()
    ProductId = models.PositiveIntegerField()
    Quantity = models .PositiveIntegerField()
    Date = models.DateTimeField(auto_now= True)

    key = models.ForeignKey(ProductsDescription,related_name='connection')

views.py

class CartApi(APIView):
"""adds item to user's cart when post functions is called"""
    serializer_class = serializers.CartSerializer

    def post(self,request):
        a = serializers.CartSerializer(data=request.data)
        if a.is_valid():
            a.save()
            return Response({'message': 'j'})
        else:
            return Response(
            a.errors, status=status.HTTP_400_BAD_REQUEST)

class CartItems(APIView):
    serializer_class = serializers.CartOnlySerializer

    def get(self,request):
    """returns the list of products in user's cart"""
        z = int(request.GET.get('q', ''))
        queryset = (models.Cart.objects.filter(UserId=z).values())

        k = []
        for i in queryset:
            p = i.get("ProductId")
            print(p)
            k.append(models.ProductsDescription.objects.filter(connection__id=p))
        print(k)
        abc = serializers.CartOnlySerializer(k, many=True)

        return JsonResponse({'pcartlist': (abc.data)})

serializer.py

class CartSerializer(serializers.ModelSerializer):
"""serialiazer for handling the post request for the cart"""   

    class Meta:
        model = models.Cart
        fields = ('id', 'UserId', 'ProductId','Quantity',)

    def create(self, validated_data):
        user_cart = models.Cart(
            UserId=validated_data.get('UserId'),
            ProductId=validated_data.get('ProductId'),
            Quantity = validated_data.get('Quantity'),
            key=models.ProductsDescription(validated_data.get('ProductId')))       

        user_cart.save()
        return user_cart

class CartListSerializer(serializers.ModelSeriaizer):
    class Meta :
        model = models.ProductsDescription
        fields =('id','category','name','price','description','specification','photos')

class CartListSerializer1(serializers.ListSerializer):
    child = CartListSerializer(allow_null =True, many = True)        


class CartOnlySerializer(serializers.ModelSerializer):
   connection = CartListSerializer1()

    class Meta:
        model = models.Cart
        fields = ('connection',)

有一个模型ProductDescription存储有关产品的所有信息,模型Cart用于保存所选项目的ProductId,UserId和Quantity。

因此,当用户收到购物车的请求时,我想发送产品信息和与之相关的数量。 我尝试在序列化程序and tried to make queries according to reverse relation as said in the documentation.

中使用反向关系

但每次尝试我都会遇到各种错误。 我不明白如何使用外键在django rest框架中使用序列化程序进行sql连接和检索信息。

1 个答案:

答案 0 :(得分:0)

你的代码打破了许多PEP-8风格的指南,我建议你阅读或重读,它会对你有所帮助,也许不是现在,但将来会有所帮助。

我强烈建议您修改所有应用程序架构和业务逻辑并使用{​​{1}}个视图,它们将为您完成所有工作。

我会把那些我希望成为你写作更好的应用程序的起点:

应用/ models.py

rest_framework.generics

应用/ serializers.py

from django.db import models


class Product(models.Model):
    ...

class CartItem(models.Model):
    user = models.ForeignKey(to=settings.AUTH_USER_MODEL)
    product = models.ForeignKey(to='Product')
    quantity = models.PositiveIntegerField(default=0)

应用/ views.py

from . import CartItem, Product


class ProductSerializer(serialziers.ModelsSerializer):
    class Meta:
        model = Product
        fields = (<your_fields>,)


class CartItemSerializer(serialziers.ModelSerializer):
    product = ProductSerializer()

    class Meta:
        model = CartItem
        fields = ('product', 'quantity', )