Reputation: 594
My goal is to delete the fk record related with the record of the given id in the endpoint.
my url
path('car-pricing/<uuid:car_id>/', car_pricing),
my model
class Pricing(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
car = models.ForeignKey(Car, related_name="pricings", on_delete=models.CASCADE)
In other words I want to delete a specific Pricing
record given the id of a Car
in my endpoint.
By requesting with an id of a Car
record I can get more than one Pricing
records.
Is it somehow possible to choose to delete a specific Pricing
based on the id?
my view(here, I do not know how to deal with delete function)
elif request.method == 'DELETE':
pricing_data = request.data
return Response(status=status.HTTP_204_NO_CONTENT)
Here the requested data is an empty QueryDict and it is ok, since there is no way to give requested data to a delete action in django rest framework
Upvotes: 0
Views: 653
Reputation: 2110
When you want to delete specific object you must have specific filter which will return just one object. As far as I see you have one to many
relation between Car
and Pricing
models, so you can't delete a specific pricing by filtering just car
field (because car can be connected to more than one pricing object). When you want to delete specific row from table with some filters you should have constraint on that table and those filters to return just one row. However you can delete records of pricing by using Pricing.object.filter(car_id=car_id).delete()
but in this case you will delete all the pricing objects which is related to that car. If you change the path('car-pricing/<uuid:car_id>/', car_pricing),
to path('car-pricing/<uuid:car_id>/<int:pk>/', car_pricing)
you can delete specific record by filtering as Pricing.objects.filter(pk=pk, car_id=car_id).delete()
or by just using path('car-pricing/<int:pk>/', car_pricing)
and Pricing.objects.filter(pk=pk).delete()
you can delete specific pricing object because pk
of this table is a unique field and also is a constraint on that table.
Upvotes: 1