skip to Main Content

Currently I am trying to figure how the post request needs to be structured to create an object in watchlist.

My models.py contains two models that are linked together via stock.

class Stock(models.Model):
    model_number = models.CharField(max_length=100, unique=True, default="")
    model = models.CharField(max_length=100)
    brand = models.CharField(max_length=100)
    msrp = models.IntegerField(default=0)

class Watchlist(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    stock = models.ManyToManyField(Stock)

This created two tables in my database one called watchlist and another called watchlist_stock. The former contains an id and a user id. The later contains id, watchlist_id, and stock_id.

Here is my serializer for the relevant view

class WatchlistAddSerializer(serializers.ModelSerializer):
    class Meta:
        model = Watchlist
        fields = ['stock']

And here is the relevant view for the post method.

@api_view(['POST'])
def watchlist_create(request):
    serializer = WatchlistAddSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save(user=request.user)
        return JsonResponse(serializer.data, status=status.HTTP_201_CREATED)
    else:
        return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

I am using axios to post on the react frontend but I am currently at a loss for how the data needs to be structured to post.

react

api.post(`/api/watchlist-create/`, {
    // Some data goes here
})

2

Answers


  1. Chosen as BEST ANSWER

    I ended up figuring it out after awhile of searching for similar problems.

        @api_view(['POST'])
        @permission_classes([IsAuthenticated])
        def watchlist_create(request, stock_id):
            // Get the stock from url
            stock = get_object_or_404(Stock, pk=stock_id)
            // Check if user has a watchlist and if not create one
            user_watchlist, created = Watchlist.objects.get_or_create(user=request.user)
            // Add the stock to the users watchlist
            user_watchlist.stock.add(stock)
            return JsonResponse({'status': 'success'}, status=status.HTTP_200_OK)
    
    const handleAdd = (id) => {
            api.post(`/api/watchlist-create/${id}`)
        }
    

  2. You can add aPrimaryKeyRelatedField field [drf-doc] to (de)serialize the stock:

    class WatchlistAddSerializer(serializers.ModelSrialzer):
        stock = serializers.PrimaryKeyRelatedField(
            many=True, queryset=Stock.objects.all()
        )
    
        class Meta:
            model = Watchlist
            fields = ['tock']

    You then list the ids of the stock as data:

    api.post(`/api/watchlist-create/`, {
        stock: [1, 4, 25]  // ids of stock objects
    })
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search