简体   繁体   中英

How can I pass an object selected by the user, to another view and retrieve a specific column from that object?

I'm trying to figure out the most efficient way to GET values inside my stock_list column from the current object that's being viewed by a user.

BucketDetail is used to retrieve the specific object selected by the user via item = self.kwargs.get('pk')

class BucketDetail(generics.RetrieveAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = BucketListSerializer
    queryset = Bucket.objects.all()

    def get_object(self, queryset=queryset, **kwargs):
        item = self.kwargs.get('pk')
        return get_object_or_404(Bucket, slug=item)

How can I pass the object instance, from BucketDetail to BucketData view, followed by getting the column, stock_list , from the current object instance?

class BucketData(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request, *args, **kwargs):
        stocks = Bucket.objects.get(stock_list)
        ...
        data = response.json()
        return Response(data, status=status.HTTP_200_OK)

above is what I have so far, stocks = Bucket.objects.get(stock_list) does not work like I thought.

models.py

class Bucket(models.Model):

    category_options = (
        ('personal', 'Personal'),
        ('social', 'Social'),
    )


    class BucketObjects(models.Manager):
        def get_queryset(self):
            return super().get_queryset()

    ...
    slug = models.SlugField(unique=True, blank=True) 
    stock_list = ArrayField(models.CharField(max_length=6,null=True),size=30,null=True)
    ...


    objects = models.Manager()
    bucketobjects = BucketObjects()

    class Meta:
        ordering = ('-created',)

    def total_stocks_calc(self):
        self.stock_count = Bucket.objects.aggregate(Sum('stock_list', distinct=True))
        self.save()



You should use model pk or your unique slug to retrieve stock_list data within your BucketData view. You also should use a serializer for the data. Pass your slug or pk from urls file to your view. Try something like this (code is not tested and can be improved):

Serializer:

class StockListSerializer(ModelSerializer):
    stock_list = serializers.ListField(child=serializers.CharField())

    class Meta:
        model = Bucket
        fields = ("stock_list",)

View:

class BucketData(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request, *args, **kwargs):
        slug = kwargs.get("slug")
        bucket_object = get_object_or_404(Bucket, slug=slug)
        serialzer = StockListSerializer(bucket_object.stock_list)
        return Response(serialzer.data, status=status.HTTP_200_OK)

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