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
I ended up figuring it out after awhile of searching for similar problems.
You can add a
PrimaryKeyRelatedField
field [drf-doc] to (de)serialize the stock:You then list the ids of the stock as data: