Home > Back-end >  How do I handle foreign key relationship in the urlpattern in the django-rest-framwork
How do I handle foreign key relationship in the urlpattern in the django-rest-framwork

Time:11-25

In my models.py I have the following classes:

class Project(models.Model):
    name = models.CharField(max_length=100)

class ProjectMaterial(models.Model):
    project = models.ForeignKey("Project", on_delete=models.CASCADE)
    material = models.CharField(max_length=150)
    units = models.IntegerField()

My serializers are like this:

class ProjectSerializer(serializers.ModelSerializer):
    class Meta:
        model = Project
        fields = "__all__"

class ProjectMaterialSerializer(serializers.ModelSerializer):
    class Meta:
        model = ProjectMaterial
        fields = "__all__"

My current views.py looks like this:

class ProjectList(generics.ListCreateAPIView):

    queryset = Project.objects.all()
    serializer_class = ProjectSerializer


class ProjectDetail(generics.RetrieveUpdateDestroyAPIView):

    queryset = Project.objects.all()
    serializer_class = ProjectSerializer


class ProjectMaterialList(generics.ListCreateAPIView):

    queryset = ProjectMaterial.objects.all()
    serializer_class = ProjectMaterialSerializer

How should I create my urlpatterns to make a PUT request to change the units value for a project with an id=1 for a material with an id=3?

CodePudding user response:

I suppose you want to change the value of a Material Object where id = 3. in this case you really dont want to add the FK to the url_patterns. instead you can send data data related to FK via a PUT request.

urlpatterns = [
    path('<id>/edit/', MaterialUpdateView.as_view(), name='material-update'),
]

If you really want to change the FK. send the data via a PUT or PATCH request like this

  data = {
      id: 3,
      project: 1,
      material: "some material"
      units: 25,
   }

CodePudding user response:

If you want to update "ProjectMaterial" record with id=3 and that has FK relationship to "Project" record with id=1. All you need is "ProjectMaterial" id in URL and the data that needs to be updated for the corresponding "Project" record(Since it is in relationship with ProjectMaterial).

urlpatterns = [
path('/material/<id>/', ProjectMaterialDetail.as_View(), name='project_material')

]

If you want to update only the "units" field of "ProjectMaterial", you just inherit UpdateModelMixin into the new view class, "ProjectMaterialDetail". You can inherit "RetrieveModelMixin" into the same class. All you need to do is to make sure you send data in correct format to the ProjectMaterial serializer in "PUT" method of "ProjectMaterialDetail" view.

{
    id: 5,
    units: 152,
}

You can override Update method in serializer or you can call "partial_update" method in "PUT" method.

  • Related