简体   繁体   中英

Django-Rest-Framework-Use of foreign key in a reverse relation

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',)

There is one model ProductDescription which stores all the info about the products and there is model Cart which is used to save the ProductId ,UserId and Quantity of the the item user selected.

So,When there is a get request by the user for their cart I want to send the information of the products and the quantity associated with it. I tried using reverse relation in serializer and tried to make queries according to reverse relation as said in the documentation.

But i was getting errors of all kind every time I tried. i have no understanding how can we use foreign keys to make sql joins and the retrieve info using serializers in django rest framework.

Your code have broken many PEP-8 style guide notes, that i suggest you read or reread, it will help you, maybe not now, but in future.

I strongly suggest you to rething all the app architecture and business logic and use rest_framework.generics views, they will do all work for you.

I will put that pieces that i would like to be your start point of writing better app:

app/models.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)

app/serializers.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', )

app/views.py

from rest_framework import generics

from .serializers import CartItemSerializer


class CartAPIView(generics.ListAPIView):
    serializer_class = CartItemSerializer

    def get_queryset(self)
        return CartItem.objects.filter(user=self.request.user)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM